#!/bin/sh
# Public ANACOM Earth evidence preview. No native binary or private application.
set -eu
umask 077
case "$(uname -s)" in Darwin|Linux) ;; *) echo "macOS or Linux required." >&2; exit 1;; esac
case "${HOME-}" in /*) ;; *) echo "A valid home directory is required." >&2;exit 1;; esac
base="$HOME/.local/share/anacom-preview"
bin="$HOME/.local/bin"
launcher="$bin/anacom-preview"
[ ! -e "$base" ] && [ ! -L "$base" ] && [ ! -e "$launcher" ] && [ ! -L "$launcher" ] || { echo "Existing preview found; nothing overwritten." >&2; exit 1; }
if command -v shasum >/dev/null 2>&1; then checksum(){ shasum -a 256 "$1" | awk '{print $1}'; }
elif command -v sha256sum >/dev/null 2>&1; then checksum(){ sha256sum "$1" | awk '{print $1}'; }
else echo "SHA-256 utility required." >&2;exit 1;fi
tmp="$(mktemp -d "${TMPDIR:-/tmp}/anacom-preview.XXXXXX")"
created=0
linked=0
cleanup(){ rm -rf "$tmp"; if [ "$created" = 1 ] && [ "$linked" = 0 ]; then rm -f "$base/earth.html" "$base/anacom-preview"; rmdir "$base" 2>/dev/null || :;fi; }
trap cleanup EXIT
trap 'exit 1' HUP INT TERM
if [ "$#" = 2 ] && [ "$1" = "--from-file" ]; then
  [ -f "$2" ] && [ ! -L "$2" ] || { echo "Expected a regular preview file." >&2;exit 1; }
  cp "$2" "$tmp/earth.html"
elif [ "$#" = 0 ]; then
  command -v curl >/dev/null 2>&1 || { echo "curl required." >&2;exit 1; }
  curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' --max-redirs 2 --connect-timeout 15 --max-time 60 --max-filesize 1000000 https://anacomai.com/preview/earth-20261202.html -o "$tmp/earth.html"
else echo "Usage: sh install-preview.sh [--from-file verified-preview.html]" >&2;exit 1;fi
[ "$(checksum "$tmp/earth.html")" = "28d987090c8385ccf69fde462925b0c0a6d249984900ea31d00f000073c1455f" ] || { echo "Preview checksum mismatch; nothing installed." >&2;exit 1; }
mkdir -p "$HOME/.local/share" "$bin"
mkdir "$base"
created=1
cp "$tmp/earth.html" "$base/earth.html"
cat > "$base/anacom-preview" <<'LAUNCH'
#!/bin/sh
set -eu
file="$HOME/.local/share/anacom-preview/earth.html"
case "${1:-earth}" in
 --version) printf '%s\n' 'ANACOM Earth public evidence preview 2026.12.02';;
 --path) printf '%s\n' "$file";;
 earth) [ -f "$file" ] || { echo "Preview file missing." >&2;exit 1; };case "$(uname -s)" in Darwin) open "$file";; Linux) command -v xdg-open >/dev/null || { echo "Open $file in your browser.";exit 1; };xdg-open "$file";; *) exit 1;;esac;;
 --help) printf '%s\n' 'anacom-preview earth | --version | --path';;
 *) echo "Unknown command. Use --help." >&2;exit 1;;
esac
LAUNCH
chmod 700 "$base/anacom-preview"
ln -s "$base/anacom-preview" "$launcher"
linked=1
printf '%s\n' "Installed public evidence preview. Run: $launcher earth"
