#!/bin/sh
# Generated by scripts/redagent/render.py. Reviewable per-user pilot installer.
set -eu
umask 077
VERSION='0.2.0'
SOURCE_COMMIT='e1e3002be85f95d4db556ffb3f68f699c5dcd085'
BASE_URL='https://github.com/OrbitusRoboticsWebSite/ORobotics/releases/download/redagent-v0.2.0-pilot'
prefix=''
archive=''
dry_run=false
fail() { printf 'RedAgent: %s\n' "$*" >&2; exit 1; }
while [ "$#" -gt 0 ]; do
    case "$1" in
        --prefix|--archive)
            [ "$#" -ge 2 ] || fail "$1 requires a path"
            case "$1" in --prefix) prefix=$2;; --archive) archive=$2;; esac
            shift 2;;
        --dry-run) dry_run=true; shift;;
        --help)
            printf '%s\n' 'RedAgent pilot installer: sh install.sh [--dry-run] [--prefix ABSOLUTE_PATH] [--archive VERIFIED_LOCAL_BUNDLE]' 'Installs for the current user. Does not launch tests or enroll in MDM.'
            exit 0;;
        *) fail "Unknown argument: $1";;
    esac
done
system=$(uname -s)
machine=$(uname -m)
# A shell running under Rosetta reports x86_64; use the native Apple Silicon bundle.
if [ "$system" = Darwin ] && [ "$(sysctl -in hw.optional.arm64 2>/dev/null || true)" = 1 ]; then machine=arm64; fi
case "$system/$machine" in
    Darwin/x86_64) filename='RedAgent-0.2.0-Darwin-x86_64.tar.gz'; expected='e8c0573d9d324740f8794aee5cd8adab97967b88c96e9e6de065cd4575af3488'; executable='RedAgent.app/Contents/MacOS/RedAgent'; api_url='https://api.github.com/repos/OrbitusRoboticsWebSite/ORobotics/releases/assets/723433706';;
    Darwin/arm64) filename='RedAgent-0.2.0-Darwin-arm64.tar.gz'; expected='a1b2cb61626b8e5b60e66c56936e79dfad05d43cc8543e09df81ee19bae5d354'; executable='RedAgent.app/Contents/MacOS/RedAgent'; api_url='https://api.github.com/repos/OrbitusRoboticsWebSite/ORobotics/releases/assets/723433707';;
    Linux/x86_64) filename='RedAgent-0.2.0-Linux-x86_64.tar.gz'; expected='355c73e25c9517a026a5e6e70f5f3f8c818dd6d383cbe35bf6957dc96218816b'; executable='RedAgent/RedAgent'; api_url='https://api.github.com/repos/OrbitusRoboticsWebSite/ORobotics/releases/assets/723433709';;
    *) fail "Unsupported platform: $system/$machine. Available: macOS arm64/x86_64 and Linux x86_64.";;
esac
if [ -z "$prefix" ]; then
    [ "$(id -u)" -ne 0 ] || fail 'Run as the signed-in desktop user, not root. MDM deployment will be configured separately.'
    [ -n "${HOME:-}" ] || fail 'HOME is not set'
    case "$system" in Darwin) prefix="$HOME/Applications/RedAgent";; Linux) prefix="$HOME/.local/share/RedAgent";; esac
fi
case "$prefix" in /*) ;; *) fail '--prefix must be an absolute path';; esac
case "$prefix" in /|*/../*|*/..|*/./*|*/.|*/) fail 'Use a dedicated install directory without a trailing slash or dot segments';; esac
url="$BASE_URL/$filename"
printf 'RedAgent %s pilot\nPlatform: %s/%s\nDownload: %s\nSHA-256: %s\nInstall to: %s\n' "$VERSION" "$system" "$machine" "$url" "$expected" "$prefix"
if "$dry_run"; then printf '%s\n' 'Preview only; no download or installation.'; exit 0; fi
if [ "$system" = Linux ]; then
    glibc=$(getconf GNU_LIBC_VERSION 2>/dev/null || true)
    case "$glibc" in 'glibc '*) ;; *) fail 'This Linux build requires glibc 2.35+ (Ubuntu 22.04 or compatible), not musl/Alpine.';; esac
    glibc=${glibc#glibc }
    awk -v v="$glibc" 'BEGIN { split(v,a,"."); exit !(a[1]>2 || (a[1]==2 && a[2]>=35)) }' || fail "glibc $glibc is too old; need 2.35+"
fi
if [ -L "$prefix" ]; then fail "Install directory is a symlink: $prefix"; fi
if [ -e "$prefix" ]; then
    [ -f "$prefix/installation.json" ] && grep -Fq '"installer": "orbitus-redagent"' "$prefix/installation.json" || fail "Existing directory is not a managed RedAgent installation: $prefix"
    if grep -Fq "$expected" "$prefix/installation.json" && [ -x "$prefix/$executable" ]; then
        printf 'RedAgent %s is already installed at %s\n' "$VERSION" "$prefix"
        exit 0
    fi
fi
parent=$(dirname "$prefix")
mkdir -p "$parent"
work=$(mktemp -d "$parent/.redagent-install.XXXXXXXX")
backup=''
cleanup() {
    result=$?
    trap - EXIT HUP INT TERM
    if [ "$result" -ne 0 ] && [ -n "$backup" ] && [ ! -e "$prefix" ]; then mv "$backup" "$prefix" || true; fi
    rm -rf "$work"
    exit "$result"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM HUP
if [ -n "$archive" ]; then
    [ -f "$archive" ] || fail "Archive not found: $archive"
    cp "$archive" "$work/bundle.tar.gz"
else
    command -v curl >/dev/null 2>&1 || fail 'curl is required'
    if ! curl --fail --show-error --location --proto '=https' --proto-redir '=https' --retry 1 --retry-all-errors --connect-timeout 20 --max-time 600 "$url" -o "$work/bundle.tar.gz"; then
        printf '%s\n' 'Retrying through the official GitHub release asset API...'
        curl --fail --show-error --location --proto '=https' --proto-redir '=https' --retry 2 --retry-all-errors --connect-timeout 20 --max-time 600 -H 'Accept: application/octet-stream' -H 'X-GitHub-Api-Version: 2022-11-28' "$api_url" -o "$work/bundle.tar.gz"
    fi
fi
if command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 256 "$work/bundle.tar.gz" | awk '{print $1}')
elif command -v sha256sum >/dev/null 2>&1; then actual=$(sha256sum "$work/bundle.tar.gz" | awk '{print $1}')
else fail 'shasum or sha256sum is required'; fi
[ "$actual" = "$expected" ] || fail 'SHA-256 mismatch; nothing was installed'
# Only the byte-for-byte, pinned release archive reaches extraction.
mkdir "$work/payload"
tar -xzf "$work/bundle.tar.gz" -C "$work/payload"
[ -x "$work/payload/$executable" ] || fail 'Verified archive is missing its executable'
cat > "$work/payload/installation.json" <<EOF
{"installer": "orbitus-redagent", "version": "$VERSION", "sourceCommit": "$SOURCE_COMMIT", "archiveSHA256": "$expected", "distribution": "development-pilot", "mdmEnrolled": false}
EOF
if [ -e "$prefix" ]; then
    backup="$prefix.backup.$(date +%Y%m%dT%H%M%S).$$"
    mv "$prefix" "$backup"
fi
mv "$work/payload" "$prefix"
printf '\nInstalled RedAgent %s.\n' "$VERSION"
if [ -n "$backup" ]; then printf 'Previous installation retained: %s\n' "$backup"; fi
if [ "$system" = Darwin ]; then
    printf 'Open in Finder: %s/RedAgent.app\n' "$prefix"
else
    printf 'Launch from your desktop terminal: "%s/RedAgent/RedAgent"\n' "$prefix"
fi
printf '%s\n' 'Pilot build; production signing/notarization pending. Follow your normal device policy.' 'MDM enrollment is not configured. Optional scanning/capture tools are installed separately.'
