#!/bin/sh
# Install the matching x86-64 Linux / Windows WSL 2 Omega compiler archive into the current user's home.
set -eu

die() {
    printf 'Omega installer: %s\n' "$*" >&2
    exit 1
}

[ "$#" -eq 1 ] || die "usage: sh $0 ARCHIVE"
[ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] ||
    die 'this compiler requires 64-bit x86-64 Linux (or Windows WSL 2)'
: "${HOME:?set HOME to your home directory}"

bindir=$HOME/.local/bin
mkdir -p -- "$bindir" || die "could not create $bindir"
stage=$(mktemp -d "$bindir/.omega-install.XXXXXXXX") || die "could not stage in $bindir"
trap 'rm -rf -- "$stage"' 0
trap 'exit 1' 1 2 15

cat -- "$1" > "$stage/archive" || die 'could not read the archive'
expected=70e247e107e75f84cb354d7b2d496fab29a47c501340a8509fc9a27024ce9f91
actual=$(sha256sum < "$stage/archive")
[ "${actual%% *}" = "$expected" ] || die 'archive SHA-256 mismatch'
tar --force-local -xOzf "$stage/archive" omc > "$stage/omc" || die 'could not extract omc'
expected_compiler=3a37688c7bdf1b0a06d5f60a0f162fbec7df21e7910067a5407786e84a3005d9
actual_compiler=$(sha256sum < "$stage/omc")
[ "${actual_compiler%% *}" = "$expected_compiler" ] || die 'compiler SHA-256 mismatch'
chmod 755 "$stage/omc"

# The hard link creates the destination atomically and refuses existing files.
if ! ln -T -- "$stage/omc" "$bindir/omc"; then
    if [ -e "$bindir/omc" ] || [ -L "$bindir/omc" ]; then
        die "could not install at $bindir/omc (an existing file will not be replaced)"
    fi
    die "could not create $bindir/omc"
fi
printf 'Installed Omega compiler at %s\n' "$bindir/omc"
