#!/bin/sh
#
# Local FBXL FreeBASIC macOS package installer.
#
# This helper installs the package that sits beside this script. It is useful
# when the architecture directory has been downloaded or mounted locally.
#

set -eu

version=1.20.1
revision=1
arch=arm64

die() {
    printf 'ERROR: %s
' "$*" >&2
    exit 1
}

warn() {
    printf 'WARNING: %s
' "$*" >&2
}

have() {
    command -v "$1" >/dev/null 2>&1
}

case "$(uname -s)" in
    Darwin) ;;
    *) die "this installer is for macOS; detected $(uname -s)" ;;
esac

case "$(uname -m)" in
    "$arch") ;;
    *) warn "this package is for macOS $arch, but this machine reports $(uname -m)" ;;
esac

script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
pkg_name="freebasic-${version}-${revision}-macos-${arch}.pkg"
pkg_file="$script_dir/$pkg_name"
sum_file="$script_dir/SHA256SUMS"

[ -f "$pkg_file" ] || die "package not found: $pkg_file"

if [ -f "$sum_file" ]; then
    expected=$(awk -v name="$pkg_name" '$2 == name { print $1 }' "$sum_file")
    if [ -n "$expected" ]; then
        if have shasum; then
            actual=$(shasum -a 256 "$pkg_file" | awk '{ print $1 }')
        elif have openssl; then
            actual=$(openssl dgst -sha256 "$pkg_file" | awk '{ print $NF }')
        else
            warn "no shasum or openssl found; skipping SHA256 verification"
            actual="$expected"
        fi

        [ "$actual" = "$expected" ] || die "SHA256 mismatch for $pkg_name"
    fi
fi

if have xattr; then
    xattr -d com.apple.quarantine "$pkg_file" 2>/dev/null || true
fi

printf 'This helper is about to run the following command with sudo:
'
printf '    sudo installer -pkg "%s" -target /
' "$pkg_file"
printf '
'
printf 'That installs the FreeBASIC macOS package into the package declared
'
printf 'system install location. It does not rebuild FreeBASIC or modify
'
printf 'the package artifact.

'

sudo installer -pkg "$pkg_file" -target /

if ! xcode-select -p >/dev/null 2>&1; then
    warn "Apple Command Line Tools were not detected."
    warn "FreeBASIC may install, but compiling native programs usually needs them."
    warn "Run: xcode-select --install"
fi
