#!/bin/sh
# Install the matching macOS (Apple Silicon) 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)" = Darwin ] && [ "$(uname -m)" = arm64 ] ||
    die 'this compiler requires macOS on Apple Silicon (arm64)'
: "${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=08735d13ca78c38c97fbbd0298acbcb73c017eb683e2cc6a252e4231203e256b
actual=$(shasum -a 256 < "$stage/archive")
[ "${actual%% *}" = "$expected" ] || die 'archive SHA-256 mismatch'
tar -xOzf "$stage/archive" omc > "$stage/omc" || die 'could not extract omc'
expected_compiler=588d55677bfd8973431ed347c8104b6c441671c2ba514e5c6a4e48d91f74f1a7
actual_compiler=$(shasum -a 256 < "$stage/omc")
[ "${actual_compiler%% *}" = "$expected_compiler" ] || die 'compiler SHA-256 mismatch'
chmod 755 "$stage/omc"
# Remove browser quarantine attribute only after both archive and binary SHA-256 digests match.
xattr -d com.apple.quarantine "$stage/omc" >/dev/null 2>&1 || true
codesign -s - -f "$stage/omc" >/dev/null 2>&1 || true

if [ -e "$bindir/omc" ] || [ -L "$bindir/omc" ]; then
    die "could not install at $bindir/omc (an existing file will not be replaced)"
fi
ln -- "$stage/omc" "$bindir/omc" || die "could not create $bindir/omc"
printf 'Installed Omega compiler at %s\n' "$bindir/omc"
