#!/bin/bash
# ITVR Log Viewer installer for macOS (Apple Silicon and Intel).
#
#   curl -fsSL https://www.itvrtechnology.co.za/assets/install-logviewer-mac.sh | bash
#
# Why a Terminal installer: files downloaded with curl are not flagged by macOS as
# "downloaded from the internet", so Gatekeeper does not block them. The program is
# signed locally (ad-hoc), which Apple Silicon requires. No Apple account is needed.
#
# What it does:
#   - installs the program in ~/Applications/LogViewer
#   - starts it in the background now and at every login (no Terminal window needed)
#   - opens http://localhost:3080 in your browser
# Your data stays in ~/Library/Application Support/LogViewer and is kept on update/uninstall.
#
# Uninstall:  curl -fsSL https://www.itvrtechnology.co.za/assets/install-logviewer-mac.sh | bash -s -- --uninstall
set -euo pipefail

BASE_URL="https://www.itvrtechnology.co.za/assets"
VERSION="1.0.0"
PORT="${LOGVIEWER_PORT:-3080}"
DEST="$HOME/Applications/LogViewer"
LABEL="za.co.itvrtechnology.logviewer"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOG="$HOME/Library/Logs/LogViewer.log"
DOMAIN="gui/$(id -u)"

say() { printf '\n==> %s\n' "$*"; }
fail() { printf '\nError: %s\n' "$*" >&2; exit 1; }

[ "$(uname -s)" = "Darwin" ] || fail "This installer is for macOS."

stop_agent() { launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true; }

if [ "${1:-}" = "--uninstall" ]; then
  say "Removing Log Viewer"
  stop_agent
  rm -f "$PLIST"
  rm -rf "$DEST"
  echo "Removed. Your data is still in ~/Library/Application Support/LogViewer (delete it yourself if you no longer need it)."
  exit 0
fi

case "$(uname -m)" in
  arm64)  ZIP="LogViewer-Mac-AppleSilicon-v$VERSION.zip" ;;
  x86_64) ZIP="LogViewer-Mac-Intel-v$VERSION.zip" ;;
  *) fail "Unsupported Mac processor: $(uname -m)" ;;
esac

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

say "Downloading $ZIP"
curl -fL --progress-bar -o "$TMP/lv.zip" "$BASE_URL/$ZIP" || fail "Download failed. Check your internet connection."
ditto -x -k "$TMP/lv.zip" "$TMP/x"
[ -f "$TMP/x/LogViewer/LogViewer" ] || fail "The download did not contain the LogViewer program."

say "Installing to $DEST"
stop_agent                      # a running program cannot be replaced
mkdir -p "$DEST" "$HOME/Library/LaunchAgents" "$HOME/Library/Logs"
cp "$TMP/x/LogViewer/LogViewer" "$DEST/LogViewer"
cp "$TMP/x/LogViewer/README-FIRST.txt" "$DEST/" 2>/dev/null || true
chmod +x "$DEST/LogViewer"
xattr -cr "$DEST" 2>/dev/null || true
codesign --force --sign - "$DEST/LogViewer" || fail "Could not sign the program (codesign failed)."

say "Setting it to start automatically at login"
cat > "$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$LABEL</string>
  <key>ProgramArguments</key>
  <array><string>$DEST/LogViewer</string></array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PORT</key><string>$PORT</string>
    <key>NO_BROWSER</key><string>1</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
  <key>StandardOutPath</key><string>$LOG</string>
  <key>StandardErrorPath</key><string>$LOG</string>
</dict>
</plist>
EOF
launchctl bootstrap "$DOMAIN" "$PLIST" || fail "Could not start Log Viewer. See $LOG"

say "Starting"
for _ in $(seq 1 30); do
  if curl -fs -o /dev/null "http://localhost:$PORT/"; then
    echo "Log Viewer is running at http://localhost:$PORT"
    open "http://localhost:$PORT"
    echo
    echo "Bookmark that address. Log Viewer now runs in the background and starts at every login."
    echo "Messages are written to $LOG"
    exit 0
  fi
  sleep 0.5
done
fail "Log Viewer did not start. See $LOG"
