#!/usr/bin/env bash
set -euo pipefail

BASE_URL="${BASE_URL:-https://www.flushnet.net/api/downloads}"
INSTALL_ROOT="${FLUSHNET_MAC_LAUNCHER_HOME:-$HOME/Library/Application Support/FlushnetRuntime/launcher}"
USER_BIN_DIR="${FLUSHNET_USER_BIN_DIR:-$HOME/.local/bin}"
LINK_NAME="$USER_BIN_DIR/flushnet"
MODE="install"
REPAIR_TARGET=""
NO_LINK=0
INSTALL_ROSETTA=0

usage() {
  cat <<'EOF'
Flushnet macOS Safe Installer

Usage:
  install-macos-safe.sh
  install-macos-safe.sh --install-dir PATH
  install-macos-safe.sh --repair /path/to/FlushnetRuntimeLauncher
  install-macos-safe.sh --repair /path/to/FlushnetRuntime.app
  install-macos-safe.sh --no-link
  install-macos-safe.sh --install-rosetta

This installer does not disable Gatekeeper. It only removes the macOS quarantine
attribute from the Flushnet launcher/app being installed or repaired, then applies
and verifies a local ad-hoc code signature.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --install-dir) INSTALL_ROOT="$2"; shift 2 ;;
    --repair) MODE="repair"; REPAIR_TARGET="$2"; shift 2 ;;
    --no-link) NO_LINK=1; shift ;;
    --install-rosetta) INSTALL_ROSETTA=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown option: $1" >&2; usage >&2; exit 2 ;;
  esac
done

[[ "$(uname -s)" == "Darwin" ]] || { echo "This installer is for macOS only." >&2; exit 2; }
command -v xattr >/dev/null 2>&1 || { echo "xattr is required." >&2; exit 2; }
command -v codesign >/dev/null 2>&1 || { echo "codesign is required." >&2; exit 2; }
command -v file >/dev/null 2>&1 || { echo "file is required." >&2; exit 2; }


ensure_rosetta_for_x86_binary() {
  local target="$1"
  [[ "$(uname -m)" == "arm64" ]] || return 0
  file "$target" 2>/dev/null | grep -q 'x86_64' || return 0
  if /usr/bin/arch -x86_64 /usr/bin/true >/dev/null 2>&1; then
    return 0
  fi
  if [[ "$INSTALL_ROSETTA" == "1" ]]; then
    echo "Installing Rosetta 2 for the x86_64 Flushnet launcher..."
    sudo /usr/sbin/softwareupdate --install-rosetta --agree-to-license
    /usr/bin/arch -x86_64 /usr/bin/true >/dev/null 2>&1 || { echo "Rosetta installation did not become available." >&2; exit 4; }
    return 0
  fi
  echo "This Apple-silicon Mac does not currently have Rosetta 2, which is required by this x86_64 Flushnet launcher." >&2
  echo "Re-run with --install-rosetta, or install Rosetta manually:" >&2
  echo "  sudo softwareupdate --install-rosetta --agree-to-license" >&2
  exit 4
}

is_flushnet_target() {
  local p="$1" b
  b="$(basename "$p")"
  [[ "$b" == "FlushnetRuntimeLauncher" || "$b" == "FlushnetRuntime.app" || "$b" == Flushnet*Runtime*.app ]]
}

repair_target() {
  local target="$1"
  [[ -e "$target" ]] || { echo "Repair target not found: $target" >&2; exit 2; }
  is_flushnet_target "$target" || { echo "Refusing to modify non-Flushnet target: $target" >&2; exit 2; }

  echo "Removing Flushnet quarantine attribute..."
  if [[ -d "$target" ]]; then
    find "$target" -exec xattr -d com.apple.quarantine {} + 2>/dev/null || true
  else
    xattr -d com.apple.quarantine "$target" 2>/dev/null || true
  fi

  echo "Applying local ad-hoc signature..."
  if [[ -d "$target" ]]; then
    codesign --force --deep --sign - "$target"
    codesign --verify --deep --strict --verbose=2 "$target"
  else
    chmod +x "$target"
    codesign --force --sign - "$target"
    codesign --verify --strict --verbose=2 "$target"
  fi

  if [[ -d "$target" ]]; then
    if find "$target" -print0 | xargs -0 xattr -p com.apple.quarantine 2>/dev/null | grep -q .; then
      echo "Quarantine attribute is still present on a nested Flushnet file after repair." >&2
      exit 3
    fi
  elif xattr -p com.apple.quarantine "$target" >/dev/null 2>&1; then
    echo "Quarantine attribute is still present after repair." >&2
    exit 3
  fi
  echo "Flushnet macOS repair completed: $target"
}

if [[ "$MODE" == "repair" ]]; then
  repair_target "$REPAIR_TARGET"
  exit 0
fi

command -v curl >/dev/null 2>&1 || { echo "curl is required." >&2; exit 2; }
command -v unzip >/dev/null 2>&1 || { echo "unzip is required." >&2; exit 2; }
command -v shasum >/dev/null 2>&1 || { echo "shasum is required." >&2; exit 2; }

TMP_DIR="$(mktemp -d)"
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT

VERSION_JSON="$TMP_DIR/version.json"
ZIP_NAME="FlushnetRuntimeLauncher-macos-onefile.zip"
ZIP_PATH="$TMP_DIR/$ZIP_NAME"

printf '[1/7] Resolving current Flushnet runtime version...\n'
curl -fsSL "$BASE_URL/version.json" -o "$VERSION_JSON"
VERSION="$(/usr/bin/plutil -extract version raw -o - "$VERSION_JSON" 2>/dev/null || true)"
if [[ -z "$VERSION" ]]; then
  VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$VERSION_JSON" | head -n1)"
fi
[[ -n "$VERSION" ]] || { echo "Unable to resolve published runtime version." >&2; exit 3; }

printf '[2/7] Downloading Flushnet runtime %s...\n' "$VERSION"
curl -fsSL "$BASE_URL/$ZIP_NAME" -o "$ZIP_PATH"

printf '[3/7] Verifying published SHA-256...\n'
SUMS="$TMP_DIR/SHA256SUMS.txt"
curl -fsSL "$BASE_URL/SHA256SUMS-$VERSION.txt" -o "$SUMS"
EXPECTED="$(awk -v n="$ZIP_NAME" '$2==n || $2=="./"n {print $1; exit}' "$SUMS")"
[[ "$EXPECTED" =~ ^[0-9a-fA-F]{64}$ ]] || { echo "Published SHA-256 entry not found for $ZIP_NAME." >&2; exit 3; }
ACTUAL="$(shasum -a 256 "$ZIP_PATH" | awk '{print $1}')"
ACTUAL_LC="$(printf '%s' "$ACTUAL" | tr '[:upper:]' '[:lower:]')"
EXPECTED_LC="$(printf '%s' "$EXPECTED" | tr '[:upper:]' '[:lower:]')"
[[ "$ACTUAL_LC" == "$EXPECTED_LC" ]] || { echo "SHA-256 verification failed." >&2; exit 3; }

printf '[4/7] Installing launcher in user Library...\n'
mkdir -p "$INSTALL_ROOT"
unzip -q -o "$ZIP_PATH" -d "$TMP_DIR/extracted"
SRC="$TMP_DIR/extracted/FlushnetRuntimeLauncher"
[[ -f "$SRC" ]] || { echo "Launcher missing from archive." >&2; exit 3; }
DST="$INSTALL_ROOT/FlushnetRuntimeLauncher"
cp -f "$SRC" "$DST"
chmod +x "$DST"

printf '[5/7] Removing quarantine only from Flushnet install directory...\n'
find "$INSTALL_ROOT" -exec xattr -d com.apple.quarantine {} + 2>/dev/null || true

printf '[6/7] Applying and verifying local ad-hoc signature...\n'
codesign --force --sign - "$DST"
codesign --verify --strict --verbose=2 "$DST"
if xattr -p com.apple.quarantine "$DST" >/dev/null 2>&1; then
  echo "Quarantine attribute remains on installed launcher." >&2
  exit 3
fi

printf '[7/7] Validating launcher...\n'
ensure_rosetta_for_x86_binary "$DST"
"$DST" version

if [[ "$NO_LINK" != "1" ]]; then
  mkdir -p "$USER_BIN_DIR"
  ln -sfn "$DST" "$LINK_NAME"
  echo "User CLI link: $LINK_NAME"
fi

echo "Installed launcher: $DST"
echo "Gatekeeper workaround: local quarantine removed; local ad-hoc signature verified."
if [[ ":$PATH:" != *":$USER_BIN_DIR:"* && "$NO_LINK" != "1" ]]; then
  echo "To use 'flushnet' directly, add this to ~/.zprofile:"
  echo "  export PATH=\"$USER_BIN_DIR:\$PATH\""
fi
