#!/bin/sh
#
# FBXL FreeBASIC macOS installer.
#
# This script is intentionally plain POSIX sh so it can be run with the
# system /bin/sh from curl, wget, or a downloaded copy.
#

set -eu

version=1.20.1
revision=1
repo_url=${FREEBASIC_REPO_URL:-https://deb.fbxl.net}

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
    arm64) arch=arm64 ;;
    x86_64) arch=x86_64 ;;
    *) die "unsupported macOS architecture: $(uname -m)" ;;
esac

pkg_name="freebasic-${version}-${revision}-macos-${arch}.pkg"
pkg_url="${repo_url}/macos/${arch}/${pkg_name}"
sum_url="${repo_url}/macos/${arch}/SHA256SUMS"

if have mktemp; then
    tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/freebasic-macos.XXXXXX")
else
    tmp_dir="${TMPDIR:-/tmp}/freebasic-macos.$$"
    mkdir -p "$tmp_dir"
fi

cleanup() {
    rm -rf "$tmp_dir" 2>/dev/null || true
}
trap cleanup EXIT HUP INT TERM

pkg_file="$tmp_dir/$pkg_name"
sum_file="$tmp_dir/SHA256SUMS"

printf 'Installing FreeBASIC %s for macOS %s
' "$version" "$arch"
printf 'Package: %s
' "$pkg_url"

if have curl; then
    curl -fL "$pkg_url" -o "$pkg_file"
    curl -fL "$sum_url" -o "$sum_file" || sum_file=""
elif have wget; then
    wget -O "$pkg_file" "$pkg_url"
    wget -O "$sum_file" "$sum_url" || sum_file=""
else
    die "curl or wget is required to download the macOS package"
fi

if [ -n "$sum_file" ] && [ -s "$sum_file" ]; then
    expected=$(awk -v name="$pkg_name" '$2 == name { print $1 }' "$sum_file")
    if [ -z "$expected" ]; then
        die "no checksum entry for $pkg_name in SHA256SUMS"
    fi

    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

    if [ "$actual" != "$expected" ]; then
        die "SHA256 mismatch for $pkg_name"
    fi
fi

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

if ! have installer; then
    die "macOS installer command not found"
fi

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

printf 'FreeBASIC macOS package install complete.
'
