#!/bin/bash
# Fresh Intel Mac setup. Stages can be resumed explicitly; failures never skip ahead.
set -euo pipefail
umask 077
fail() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
ask() { local a; printf '%s [y/N] ' "$*" >/dev/tty; IFS= read -r a </dev/tty; case "$a" in y|Y|yes|YES) return 0;; *) return 1;; esac; }
help() {
    cat <<'EOF'
Usage: /bin/bash setup-migration.sh PACKAGE STAGE
Stages: --plan, --all, --dependencies, --files, --python, --database, --validate
--all runs dependencies, files, Python, database restore, then validation.
Run from Terminal as kinsleypetit-homme on the CLEAN Intel Mac, not with sudo.
Licensed applications require their vendor installers and account activation.
No production services or scheduled email jobs are automatically enabled.
EOF
}
if [ "${1:-}" = --help ] || [ "$#" -ne 2 ]; then help; exit 0; fi
stage="$2"
case "$stage" in --plan|--all|--dependencies|--files|--python|--database|--validate) ;; *) fail 'Unknown stage';; esac
[ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = x86_64 ] || fail 'Requires an Intel Mac.'
[ "$EUID" -ne 0 ] && [ "$(id -un)" = kinsleypetit-homme ] || fail 'Run as kinsleypetit-homme, without sudo.'
[ "$HOME" = /Users/kinsleypetit-homme ] || fail 'Unexpected home path.'
package=$(cd "$1" && pwd -P)
here=$(cd "$(dirname "$0")" && pwd -P)
project=/usr/local/var/www/megatron
audit="$here/audit"
brew=/usr/local/bin/brew
php=/usr/local/opt/php@8.3/bin/php
pg=/usr/local/opt/postgresql@14/bin
export PATH="/usr/local/opt/php@8.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
export HOMEBREW_NO_AUTO_UPDATE=1
mkdir_prompt() {
    [ -d "$1" ] && return 0
    ask "Missing folder $1. Create it and any missing parents?" || fail 'Folder creation declined.'
    /bin/mkdir -p "$1"
}
quiet_servers() {
    if /usr/bin/pgrep -x 'httpd|php-fpm|postgres' >/dev/null 2>&1; then
        fail 'Stop existing Apache, PHP-FPM and PostgreSQL before this stage. This is a clean-machine setup tool.'
    fi
}
dependencies() {
    quiet_servers
    if ! /usr/bin/xcode-select -p >/dev/null 2>&1; then
        ask 'Open the Apple Command Line Tools installer?' || fail 'Command Line Tools required.'
        /usr/bin/xcode-select --install
        fail 'Finish the Apple installer, then rerun --dependencies or --all.'
    fi
    if [ ! -x "$brew" ]; then
        ask 'Run the preserved Intel-compatible official Homebrew installer for /usr/local?' || fail 'Homebrew installation declined.'
        # Current upstream HEAD rejects Intel. Use this reviewed, immutable upstream revision.
        installer="$here/homebrew-install-intel.sh"
        [ -f "$installer" ] || fail 'Missing preserved Homebrew installer.'
        digest=$(/usr/bin/shasum -a 256 "$installer" | /usr/bin/awk '{print $1}')
        [ "$digest" = 12479a24be3f5307eecac7cde670fad7118640f031229e964f544b1367b52a41 ] || fail 'Homebrew installer checksum mismatch.'
        /bin/bash "$installer"
    fi
    [ "$("$brew" --prefix)" = /usr/local ] || fail 'Expected Intel Homebrew prefix /usr/local.'
    ask 'Install httpd, PHP 8.3, PostgreSQL 14, Python 3.11/3.14, ExifTool, Ghostscript, acme.sh and Bash?' || fail 'Dependency installation declined.'
    "$brew" install httpd php@8.3 postgresql@14 python@3.11 python@3.14 exiftool ghostscript acme.sh bash
    "$php" -n -r 'exit(PHP_MAJOR_VERSION === 8 && PHP_MINOR_VERSION === 3 ? 0 : 1);'
    "$pg/pg_ctl" --version | /usr/bin/grep -q ' 14\.' || fail 'PostgreSQL major version mismatch.'
    if [ ! -f /usr/local/var/postgresql@14/PG_VERSION ]; then
        mkdir_prompt /usr/local/var/postgresql@14
        "$pg/initdb" -D /usr/local/var/postgresql@14 --encoding=UTF8 --locale=en_CA.UTF-8 --auth=trust
    fi
    # Install Composer using PHP 8.3, avoiding a second PHP major via its brew formula.
    composer_dir="$HOME/.local/share/megatron"
    mkdir_prompt "$composer_dir"
    ask 'Install Composer using its officially checksum-verified installer?' || fail 'Composer installation declined.'
    /usr/bin/curl -fLsS https://getcomposer.org/installer -o "$composer_dir/composer-setup.php"
    expected=$(/usr/bin/curl -fLsS https://composer.github.io/installer.sig)
    actual=$("$php" -n -r 'echo hash_file("sha384", $argv[1]);' "$composer_dir/composer-setup.php")
    [ "$actual" = "$expected" ] || fail 'Composer installer checksum mismatch.'
    "$php" "$composer_dir/composer-setup.php" --install-dir="$composer_dir" --filename=composer.phar
    /bin/rm "$composer_dir/composer-setup.php"
    echo 'Open-source dependencies installed. Exact Homebrew patch versions may differ from the old Mac.'
}
files() { quiet_servers; /bin/bash "$here/restore-migration.sh" "$package" --apply; }
python_setup() {
    quiet_servers
    for kind in pymupdf rembg; do
        if [ "$kind" = pymupdf ]; then
            target="$HOME/python-venvs/pymupdf-audit"
            base=/usr/local/opt/python@3.14/bin/python3.14
            requirements="$audit/pymupdf-audit-installed-packages.txt"
        else
            target="$HOME/rembg-env"
            base=/usr/local/opt/python@3.11/bin/python3.11
            requirements="$audit/rembg-installed-packages.txt"
        fi
        [ -x "$base" ] || fail "Missing Python interpreter: $base"
        [ -f "$requirements" ] && [ -s "$here/wheels/$kind/SHA256SUMS" ] || fail "Missing pinned Python requirements/wheels for $kind."
        (cd "$here/wheels/$kind" && /usr/bin/shasum -a 256 -c SHA256SUMS)
        if [ -e "$target" ]; then
            [ ! -L "$target" ] || fail "Refusing symlink environment: $target"
            saved="$target.before-migration-$(date +%Y%m%d-%H%M%S)"
            [ ! -e "$saved" ] || fail "Archive already exists: $saved"
            ask "Keep existing $target at $saved and create a fresh environment?" || fail 'Python rebuild declined.'
            /bin/mv "$target" "$saved"
        fi
        mkdir_prompt "$target"
        # Fresh-machine creation necessarily uses each Homebrew base interpreter.
        "$base" -m venv "$target"
        "$target/bin/python" -m pip install --no-index --find-links "$here/wheels/$kind" -r "$requirements"
        "$target/bin/python" -m pip check
    done
    "$HOME/python-venvs/pymupdf-audit/bin/python" -c 'import pymupdf; print("PyMuPDF", pymupdf.VersionBind)'
    "$HOME/rembg-env/bin/python" -c 'import cv2, numpy, onnxruntime, rembg; from PIL import Image; assert not cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml").empty(); print("Image-processing imports and face cascade OK")'
    [ -s "$HOME/.u2net/bria-rmbg.onnx" ] || fail 'Missing restored background-removal model.'
    # Instantiate the actual model without downloading a replacement.
    "$HOME/rembg-env/bin/python" -c 'from pathlib import Path; import onnxruntime as o; p=Path.home()/".u2net/bria-rmbg.onnx"; s=o.InferenceSession(str(p), providers=["CPUExecutionProvider"]); print("Background model loads:", len(s.get_inputs()), "input(s)")'
}
database() { /bin/bash "$here/restore-migration-databases.sh" "$package" --apply; }
validate() {
    export PDFLIBLICENSEFILE=/usr/local/etc/pdflib/licensekeys.txt
    "$php" -r '$required=["PDFlib","pdo_pgsql","gd","curl","mbstring","intl","sodium","openssl","fileinfo","exif","zip","dom"]; foreach($required as $e){if(!extension_loaded($e)){fwrite(STDERR,"Missing PHP extension: $e\n");exit(1);}} echo "PHP extensions OK\n";'
    [ -s "$PDFLIBLICENSEFILE" ] || fail 'Missing PDFlib license file.'
    "$php" "$HOME/.local/share/megatron/composer.phar" install --working-dir="$project" --no-interaction --prefer-dist
    "$php" "$HOME/.local/share/megatron/composer.phar" check-platform-reqs --working-dir="$project"
    /usr/local/opt/httpd/bin/httpd -t
    /usr/local/opt/php@8.3/sbin/php-fpm -t
    pending=0
    for app in '/Applications/Adobe Photoshop 2026/Adobe Photoshop 2026.app' '/Applications/Adobe Illustrator 2026/Adobe Illustrator.app' /Applications/BCStudio.app; do
        if [ ! -d "$app" ]; then echo "VENDOR INSTALL REQUIRED: $app"; pending=1; fi
    done
    [ "$pending" = 0 ] || fail 'Install the recorded vendor application versions and rerun --validate. Do not substitute an untested application version silently.'
    echo 'Basic setup checks passed. Validate Adobe/BCStudio/PDFlib activation, PDF rendering, fonts, camera and Automation permissions through the real workflows.'
    echo 'All production LaunchAgents remain disabled. Follow the migration guide to enable services, with email scheduling last.'
}
if [ "$stage" = --plan ]; then
    help
    echo 'Order: Homebrew/dependencies -> files/settings -> fresh pinned Python environments -> databases/roles -> validation.'
    echo 'The full file backup and licensed application installers must be available before --all.'
    exit 0
fi
[ -t 0 ] && [ -t 1 ] || fail 'Run installation interactively from Terminal.'
log=$(/usr/bin/mktemp "$HOME/megatron-setup-$(date +%Y%m%d-%H%M%S).XXXXXX")
exec > >(/usr/bin/tee -a "$log") 2>&1
trap 'printf "Setup stopped at line %s. Log: %s. Resume the failed stage after resolving the error.\n" "$LINENO" "$log" >&2' ERR
case "$stage" in
    --all)
        # Check package completeness before installing anything.
        /bin/bash "$here/restore-migration.sh" "$package" --plan
        /bin/bash "$here/restore-migration-databases.sh" "$package" --plan
        dependencies; files; python_setup; database; validate ;;
    --dependencies) dependencies ;;
    --files) files ;;
    --python) python_setup ;;
    --database) database ;;
    --validate) validate ;;
esac
