#!/bin/sh
# Install the matching 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)" = aarch64 ] ||
    die 'this compiler requires 64-bit Arm Linux'
: "${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=47990e5333737e157faae09d47f9faf3fc87bed58bef7fe8a8fec729a78f3c0a
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=34d611ca0415eab1728d3234911d90e74af17ba9ab0c581d559f48274d7ca6d3
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"
