#!/bin/bash
# ===========================================================================
#  Team AA Media Save - one-line installer (macOS)
#
#  Usage:
#      curl -fsSL https://<your-host>/install.sh | bash
#
#  What it does (and nothing else):
#    1. Downloads the small installer payload (extension + engine, ~100 KB).
#    2. Verifies its SHA-256 when a checksum is baked in, so a tampered or
#       truncated download is rejected instead of executed.
#    3. Unpacks it into a private temp folder and hands over to
#       Install-Mac.command - the same installer the .dmg ships.
#    4. Deletes the temp folder when the installer exits.
#
#  Nothing is written outside ~/Applications, ~/Library/LaunchAgents and the
#  temp folder, and no admin password is ever requested.
#
#  Overrides (all optional):
#      TEAMAA_PAYLOAD_URL      download address of TeamAA-Media-Save-payload.tar.gz
#      TEAMAA_PAYLOAD_SHA256   expected checksum (set automatically when packaged)
#      TEAMAA_NO_UI=1          do not open the browser or Finder
#      TEAMAA_PORT=8787        engine port
#
#  Prefer to read before you run:
#      curl -fsSL https://<your-host>/install.sh -o install.sh
#      less install.sh && bash install.sh
# ===========================================================================
set -uo pipefail

# Replaced by package.sh when you build with --payload-url.
PAYLOAD_URL="https://teamaastudios.com/downloads/TeamAA-Media-Save-payload.tar.gz"
PAYLOAD_SHA256="f92f4bd641dd1fe6ef8458f568d102f2347d99f6aaafb1eb1ea67d6f46012a34"

PAYLOAD_URL="${TEAMAA_PAYLOAD_URL:-$PAYLOAD_URL}"
PAYLOAD_SHA256="${TEAMAA_PAYLOAD_SHA256:-$PAYLOAD_SHA256}"
PAYLOAD_NAME="Team AA Media Save"

die() {
  boot_loader_stop
  printf '\n  Something went wrong: %s\n' "$*" >&2
  printf '  Nothing was installed. You can safely try again.\n\n' >&2
  exit 1
}

say() { printf '%s\n' "$*"; }

# ---------------------------------------------------------------------------
#  Boot screen: the same monochrome ASCII torus used by Install-Mac.command,
#  shown while the small payload is on its way down. It is decorative only.
# ---------------------------------------------------------------------------

TAA_BOOT_PID=""
TAA_BOOT_DIR=""
TAA_BOOT_ACTIVE=0

boot_loader_supported() {
  [ "${TEAMAA_PLAIN:-0}" = "1" ] && return 1
  [ -n "${NO_COLOR:-}" ] && return 1
  [ "${TERM:-dumb}" != "dumb" ] || return 1
  [ -t 1 ] || return 1
  [ -c /dev/tty ] || return 1
  return 0
}

boot_loader_start() {
  local cols="" rows="" size usable text_row
  boot_loader_supported || return 0

  size="$(stty size </dev/tty 2>/dev/null || true)"
  if [ -n "$size" ]; then
    rows="${size%% *}"
    cols="${size##* }"
  fi
  case "$cols" in ''|*[!0-9]*) cols="$(tput cols 2>/dev/null || true)" ;; esac
  case "$rows" in ''|*[!0-9]*) rows="$(tput lines 2>/dev/null || true)" ;; esac
  case "$cols" in ''|*[!0-9]*) cols=80 ;; esac
  case "$rows" in ''|*[!0-9]*) rows=24 ;; esac
  [ "$cols" -lt 48 ] && cols=48
  [ "$rows" -lt 18 ] && rows=18

  usable=$((rows - 9))
  [ "$usable" -gt 24 ] && usable=24
  [ "$usable" -lt 9 ] && usable=9
  text_row=$((usable + 3))

  TAA_BOOT_DIR="$(mktemp -d "${TMPDIR:-/tmp}/teamaa-boot.XXXXXX")" || return 0
  cat >"$TAA_BOOT_DIR/boot.awk" <<'AWK'
BEGIN {
  pi = 3.14159265358979323846
  glyphs = ".,-~:;=!*#$@"

  usable = rows - 9
  if (usable > 24) usable = 24
  if (usable < 9) usable = 9
  scale = usable / 36.0
  xs = 50 * scale
  ys = 25 * scale
  gw = cols - 2
  cx = int(gw / 2)
  cy = 2 + int(usable / 2)

  header = "team aa media save"
  header_r = "[installer]"
  footer = "[no admin password]"
  footer_r = "[teamaastudios.com]"
  label = "[2/3] downloading the installer"

  while (1) {
    f = dir "/stop"
    if ((getline v < f) >= 0) { close(f); break }
    close(f)

    A = frame * 0.10
    B = frame * 0.115
    sa = sin(A); ca = cos(A); sb = sin(B); cb = cos(B)

    for (k = 0; k < rows * cols; k++) { ch[k] = " "; z[k] = 0 }
    for (j = 0; j < 2 * pi; j += 0.05) {
      e = cos(j); f2 = sin(j)
      for (i = 0; i < 2 * pi; i += 0.03) {
        n = sin(i); o = cos(i)
        y = e + 2
        g = 1 / (n * y * sa + f2 * ca + 5)
        v2 = n * y * ca - f2 * sa
        x = int(cx + xs * g * (o * y * sb - v2 * cb))
        w = int(cy + ys * g * (o * y * cb + v2 * sb))
        if (w >= 0 && w < rows && x >= 0 && x < gw) {
          tt = x + cols * w
          b = int(8 * ((f2 * sa - n * e * ca) * sb - n * e * sa - f2 * ca - o * e * cb))
          if (g > z[tt]) {
            z[tt] = g
            ch[tt] = substr(glyphs, (b > 0 ? b : 0) + 1, 1)
          }
        }
      }
    }

    printf "\033[H"
    for (r = 0; r < rows; r++) {
      if (r == 0) {
        printf "%s  %s%s", ink, header, reset
        if (cols > 34) {
          pad = cols - 4 - length(header) - length(header_r)
          if (pad < 1) pad = 1
          printf "%" pad "s%s%s%s", "", dim, header_r, reset
        }
        printf "\033[K"
      } else if (r == rows - 1) {
        printf "%s  %s%s", dim, footer, reset
        if (cols > 48) {
          pad = cols - 4 - length(footer) - length(footer_r)
          if (pad < 1) pad = 1
          printf "%" pad "s%s%s", "", footer_r, reset
        }
        printf "\033[K"
      } else if (r == text_row) {
        printf "%s%sloading%s\033[K", dim, centre("loading"), reset
      } else if (r == text_row + 2) {
        printf "%s%s%s%s\033[K", dim, centre(label), label, reset
      } else {
        line = ""
        for (c = 0; c < gw; c++) line = line ch[r * cols + c]
        sub(/[ ]+$/, "", line)
        printf "%s%s%s\033[K", ink, line, reset
      }
      if (r < rows - 1) printf "\n"
    }
    fflush()
    frame++
    system("sleep 0.10")
  }
}

function centre(s,   n) {
  n = int((cols - length(s)) / 2)
  if (n < 0) n = 0
  return sprintf("%" n "s", "")
}
AWK

  printf '\033[2J\033[H\033[?25l\033[40m\033[97m'
  awk -v dir="$TAA_BOOT_DIR" -v cols="$cols" -v rows="$rows" \
      -v text_row="$text_row" \
      -v ink=$'\033[97m' -v dim=$'\033[2m' -v reset=$'\033[0m' \
      -f "$TAA_BOOT_DIR/boot.awk" >/dev/tty &
  TAA_BOOT_PID=$!
  TAA_BOOT_ACTIVE=1
}

boot_loader_stop() {
  [ "$TAA_BOOT_ACTIVE" = "1" ] || return 0
  : >"$TAA_BOOT_DIR/stop" 2>/dev/null || true
  wait "$TAA_BOOT_PID" 2>/dev/null || true
  TAA_BOOT_PID=""
  TAA_BOOT_ACTIVE=0
  rm -rf "$TAA_BOOT_DIR"
  printf '\033[0m\033[?25h'
}

# ---------------------------------------------------------------------------
# 1. Local mode: if this script sits next to an unpacked payload (for example
#    right after cloning or unzipping the project), skip the download entirely.
# ---------------------------------------------------------------------------
# Only trusted when this script is a real file on disk next to the payload (for
# example `bash install.sh` inside the project). A piped script never looks at
# the current folder, so an unrelated project cannot be installed by accident.
is_payload_dir() {
  local dir="${1:-}"
  [ -n "$dir" ] && [ -f "$dir/Install-Mac.command" ] || return 1
  [ -f "$dir/Extension/manifest.json" ] || [ -f "$dir/manifest.json" ]
}

LOCAL_ROOT=""
if [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ]; then
  SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  is_payload_dir "$SELF_DIR" && LOCAL_ROOT="$SELF_DIR"
fi
if [ -n "$LOCAL_ROOT" ]; then
  say "Using the installer files already on this disk: $LOCAL_ROOT"
  exec /bin/bash "$LOCAL_ROOT/Install-Mac.command"
fi

# ---------------------------------------------------------------------------
# 2. Refuse to guess a download address.
# ---------------------------------------------------------------------------
case "$PAYLOAD_URL" in
  __PAYLOAD_URL__|"")
    cat >&2 <<'EOF'

  No download address is configured in this copy of install.sh.

  Build the one-liner properly with:

      ./package.sh --payload-url https://your-host/TeamAA-Media-Save-payload.tar.gz

  or point it at any host you control right now:

      TEAMAA_PAYLOAD_URL="https://your-host/TeamAA-Media-Save-payload.tar.gz" \
        bash install.sh

EOF
    exit 2
    ;;
esac

if [ "$(uname -s)" != "Darwin" ]; then
  die "this installer is for macOS only."
fi

# ---------------------------------------------------------------------------
# 3. Download, verify, unpack.
# ---------------------------------------------------------------------------
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/teamaa-install.XXXXXX")" || die "could not create a temp folder."
cleanup() { boot_loader_stop; rm -rf "$TMP_DIR"; }
trap cleanup EXIT INT TERM

if boot_loader_supported; then
  boot_loader_start
else
  say ""
  say "  team aa media save · installer"
  say "  [2/3] downloading the installer (about 100 KB)"
  say ""
fi

if [ "$TAA_BOOT_ACTIVE" = "1" ]; then
  if ! curl -fLsS --connect-timeout 20 --retry 3 --retry-delay 2 \
      -o "$TMP_DIR/payload.tgz" "$PAYLOAD_URL" 2>"$TMP_DIR/curl.err"; then
    boot_loader_stop
    [ -s "$TMP_DIR/curl.err" ] && sed 's/^/  /' "$TMP_DIR/curl.err" >&2
    die "the download failed ($PAYLOAD_URL)."
  fi
else
  curl -fL --progress-bar --connect-timeout 20 --retry 3 --retry-delay 2 \
    -o "$TMP_DIR/payload.tgz" "$PAYLOAD_URL" \
    || die "the download failed ($PAYLOAD_URL)."
fi

if [ -n "$PAYLOAD_SHA256" ] && [ "$PAYLOAD_SHA256" != "__PAYLOAD_SHA256__" ]; then
  ACTUAL_SHA="$(shasum -a 256 "$TMP_DIR/payload.tgz" 2>/dev/null | awk '{print $1}')"
  [ -n "$ACTUAL_SHA" ] || die "could not checksum the download."
  if [ "$ACTUAL_SHA" != "$PAYLOAD_SHA256" ]; then
    die "the download does not match its checksum. Re-run the command, and if it keeps failing, ask for the .dmg instead."
  fi
  [ "$TAA_BOOT_ACTIVE" = "1" ] || say "  Checksum verified."
fi

tar -xzf "$TMP_DIR/payload.tgz" -C "$TMP_DIR" 2>/dev/null \
  || die "the download could not be unpacked."

INSTALLER=""
for candidate in \
  "$TMP_DIR/$PAYLOAD_NAME/Install-Mac.command" \
  "$TMP_DIR/Team AA Media Save/Install-Mac.command" \
  "$TMP_DIR/TeamAA-Media-Save/Install-Mac.command" \
  "$TMP_DIR/Install-Mac.command"
do
  if [ -f "$candidate" ]; then
    INSTALLER="$candidate"
    break
  fi
done
if [ -z "$INSTALLER" ]; then
  INSTALLER="$(find "$TMP_DIR" -maxdepth 3 -name 'Install-Mac.command' 2>/dev/null | head -n 1)"
fi
[ -n "$INSTALLER" ] || die "the package is incomplete (no Install-Mac.command inside)."

chmod +x "$INSTALLER" 2>/dev/null || true

# ---------------------------------------------------------------------------
# 4. Hand over to the real installer. It prints its own progress, sets up the
#    private tools, registers the LaunchAgent, and verifies the engine.
# ---------------------------------------------------------------------------
if [ "$TAA_BOOT_ACTIVE" = "1" ]; then
  boot_loader_stop
else
  say ""
fi

# Give the installer the terminal, not the script pipe. Otherwise a child that
# reads stdin (the final "press return" prompt, for example) would swallow the
# rest of this file while bash is still reading it.
if [ -t 1 ] && [ -c /dev/tty ]; then
  /bin/bash "$INSTALLER" </dev/tty
else
  /bin/bash "$INSTALLER" </dev/null
fi
STATUS=$?

if [ "$STATUS" -ne 0 ]; then
  printf '\n  The installer stopped with an error. Details are above.\n\n' >&2
fi

exit "$STATUS"
