#!/bin/sh
# LightCode installer for macOS and Linux.
#
#   curl -fsSL https://lightcode.live/install.sh | sh
#
# Options (pass after `sh -s --`):
#   --appimage     Linux: AppImage in ~/.local (default; no root needed, auto-updates)
#   --deb          Linux: .deb package via apt/dpkg (Debian, Ubuntu; needs sudo)
#   --uninstall    Remove LightCode installed by this script
#   --dry-run      Download and verify only; install nothing
#   -h, --help     Show this help
#
#   curl -fsSL https://lightcode.live/install.sh | sh -s -- --deb
#
# Environment: LIGHTCODE_FEED overrides the release feed (default https://lightcode.live/releases).
set -eu

FEED="${LIGHTCODE_FEED:-https://lightcode.live/releases}"
FEED="${FEED%/}"
MODE=""
DRY_RUN=0
UNINSTALL=0

say() { printf '%s\n' "$*"; }
die() { printf 'LightCode install: %s\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }

usage() {
  cat <<'HELP'
LightCode installer for macOS and Linux

  curl -fsSL https://lightcode.live/install.sh | sh
  curl -fsSL https://lightcode.live/install.sh | sh -s -- --deb

Options:
  --appimage     Linux: AppImage in ~/.local (default; no root needed, auto-updates)
  --deb          Linux: .deb package via apt (Debian, Ubuntu; needs sudo)
  --uninstall    Remove LightCode installed by this script
  --dry-run      Download and verify only; install nothing
  -h, --help     Show this help
HELP
}

while [ $# -gt 0 ]; do
  case "$1" in
    --appimage) MODE=appimage ;;
    --deb) MODE=deb ;;
    --uninstall) UNINSTALL=1 ;;
    --dry-run) DRY_RUN=1 ;;
    -h|--help) usage; exit 0 ;;
    *) die "unknown option: $1 (try --help)" ;;
  esac
  shift
done

OS="${LIGHTCODE_OS:-$(uname -s)}"
RAW_ARCH="${LIGHTCODE_ARCH:-$(uname -m)}"
case "$RAW_ARCH" in
  x86_64|amd64) ARCH=x64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) die "unsupported CPU architecture: $RAW_ARCH" ;;
esac
case "$OS" in
  Darwin) PLATFORM=mac ;;
  Linux) PLATFORM=linux ;;
  *) die "unsupported system: $OS. On Windows use: irm https://lightcode.live/install.ps1 | iex" ;;
esac
if [ "$PLATFORM" = linux ] && [ "$ARCH" != x64 ]; then
  die "Linux builds are x64 only for now (this machine is $RAW_ARCH)."
fi

# ---- helpers -------------------------------------------------------------------------------
fetch() { # fetch <url> <dest>
  if have curl; then curl -fsSL --retry 3 -o "$2" "$1"
  elif have wget; then wget -q -O "$2" "$1"
  else die "curl or wget is required"
  fi
}

fetch_progress() { # fetch_progress <url> <dest>: like fetch, with a progress bar when a terminal is attached
  if [ -t 2 ]; then
    if have curl; then curl -fL --retry 3 --progress-bar -o "$2" "$1"; return; fi
    if have wget; then wget -q --show-progress -O "$2" "$1"; return; fi
  fi
  fetch "$1" "$2"
}

human_size() { # bytes -> "98.4 MB"
  awk -v b="$1" 'BEGIN { split("B KB MB GB", u, " "); i=1; while (b >= 1024 && i < 4) { b /= 1024; i++ } printf (i == 1 ? "%d %s" : "%.1f %s"), b, u[i] }'
}

step() { STEP=$((STEP + 1)); say ""; say "[$STEP/$STEPS] $*"; }
STEP=0
STEPS=4
[ "$DRY_RUN" = 1 ] && STEPS=3

sha512_b64() { # base64 SHA-512 of a file (the format used by latest-*.yml)
  if have openssl; then openssl dgst -sha512 -binary "$1" | openssl base64 -A
  elif have sha512sum && have base64 && have xxd; then sha512sum "$1" | cut -d' ' -f1 | xxd -r -p | base64 | tr -d '\n'
  else return 1
  fi
}

TMP="$(mktemp -d "${TMPDIR:-/tmp}/lightcode-install.XXXXXX")"
trap 'rm -rf "$TMP"' EXIT INT TERM

# ---- uninstall -----------------------------------------------------------------------------
if [ "$UNINSTALL" = 1 ]; then
  if [ "$PLATFORM" = mac ]; then
    for d in /Applications "$HOME/Applications"; do
      if [ -d "$d/LightCode.app" ]; then rm -rf "$d/LightCode.app"; say "Removed $d/LightCode.app"; fi
    done
    rm -f "$HOME/.local/bin/lightcode"
  else
    rm -rf "$HOME/.local/opt/lightcode" "$HOME/.local/bin/lightcode" \
      "$HOME/.local/share/applications/lightcode.desktop" \
      "$HOME/.local/share/icons/hicolor/180x180/apps/lightcode.png"
    say "Removed the AppImage install from ~/.local"
    if have dpkg && dpkg -s lightcode >/dev/null 2>&1; then
      say "A .deb install is also present: sudo apt-get remove lightcode"
    fi
  fi
  say "Your projects and LightCode data are untouched."
  exit 0
fi

# ---- find the latest build in the release feed ----------------------------------------------
step "Checking the latest LightCode release..."
fetch "$FEED/latest-$PLATFORM.yml" "$TMP/latest.yml" \
  || die "no $PLATFORM build is published yet at $FEED (latest-$PLATFORM.yml not found)."

VERSION="$(awk '/^version:/ {gsub(/["'"'"']/, "", $2); print $2; exit}' "$TMP/latest.yml")"
[ -n "$VERSION" ] || die "could not read the version from latest-$PLATFORM.yml"

# "<file> <sha512>" per `files:` entry
awk '
  /^[ \t]*-[ \t]+url:/ { u=$3; gsub(/["'"'"']/, "", u) }
  /^[ \t]+sha512:/ && u != "" { s=$2; gsub(/["'"'"']/, "", s); print u " " s; u="" }
' "$TMP/latest.yml" > "$TMP/files.txt"

pick() { grep -E -e "$1" "$TMP/files.txt" | head -n 1 || true; }

if [ "$PLATFORM" = mac ]; then
  ENTRY="$(pick "-mac-$ARCH\\.zip ")"
else
  [ -n "$MODE" ] || MODE=appimage
  if [ "$MODE" = deb ]; then ENTRY="$(pick '\.deb ')"; else ENTRY="$(pick '\.AppImage ')"; fi
fi
[ -n "$ENTRY" ] || die "no matching file for $PLATFORM/$ARCH${MODE:+/$MODE} in the release feed"
FILE="${ENTRY% *}"
WANT="${ENTRY##* }"
case "$FILE" in */*|*..*|'') die "unexpected file name in feed: $FILE" ;; esac

say "      Found LightCode $VERSION for $PLATFORM/$ARCH${MODE:+ ($MODE)}"
step "Downloading $FILE ..."
fetch_progress "$FEED/$FILE" "$TMP/$FILE"
SIZE="$(wc -c < "$TMP/$FILE" | tr -d ' ')"
say "      Downloaded $(human_size "$SIZE")"

step "Verifying the download (SHA-512)..."
if GOT="$(sha512_b64 "$TMP/$FILE")"; then
  [ "$GOT" = "$WANT" ] || die "checksum mismatch for $FILE; the download was not installed."
  say "      Checksum OK"
else
  die "cannot verify the download (install openssl, or sha512sum + xxd + base64)."
fi

if [ "$DRY_RUN" = 1 ]; then
  say "Dry run: LightCode $VERSION ($PLATFORM/$ARCH${MODE:+/$MODE}) downloaded and verified; nothing installed."
  exit 0
fi

# ---- install: macOS -------------------------------------------------------------------------
if [ "$PLATFORM" = mac ]; then
  if [ -w /Applications ]; then DEST=/Applications; else DEST="$HOME/Applications"; mkdir -p "$DEST"; fi
  step "Installing into $DEST ..."
  say "      Unpacking..."
  ditto -x -k "$TMP/$FILE" "$TMP/unpacked"
  APP="$(find "$TMP/unpacked" -maxdepth 1 -name '*.app' | head -n 1)"
  [ -n "$APP" ] || die "the archive did not contain an .app"
  if pgrep -x LightCode >/dev/null 2>&1; then
    say "      Closing the running LightCode..."
    osascript -e 'quit app "LightCode"' >/dev/null 2>&1 || true
    sleep 2
  fi
  say "      Copying LightCode.app..."
  rm -rf "$DEST/LightCode.app"
  ditto "$APP" "$DEST/LightCode.app"
  say "      Preparing the app for macOS (quarantine flag, ad-hoc signature)..."
  # Files fetched with curl carry no quarantine flag, but clear it anyway; then re-seal ad hoc so
  # Apple Silicon accepts the (unsigned) app.
  xattr -dr com.apple.quarantine "$DEST/LightCode.app" 2>/dev/null || true
  codesign --force --deep --sign - "$DEST/LightCode.app" >/dev/null 2>&1 || true
  # `lightcode` terminal command (remote control etc.): runs the app binary, which handles it in-process
  BIN="$HOME/.local/bin"
  mkdir -p "$BIN"
  say "      Adding the 'lightcode' terminal command..."
  printf '#!/bin/sh\nexec "%s/LightCode.app/Contents/MacOS/LightCode" "$@"\n' "$DEST" > "$BIN/lightcode"
  chmod 755 "$BIN/lightcode"
  say ""
  say "LightCode $VERSION installed in $DEST/LightCode.app"
  say "Start it with:  open -a LightCode"
  case ":$PATH:" in
    *":$BIN:"*) say "Terminal command:  lightcode remote on" ;;
    *) say "Terminal command: add $BIN to your PATH, then run  lightcode remote on" ;;
  esac
  say "To update later, run this installer again."
  exit 0
fi

# ---- install: Linux -------------------------------------------------------------------------
if [ "$MODE" = deb ]; then
  have apt-get || die "--deb needs apt-get (Debian/Ubuntu). Use --appimage on other distributions."
  if [ "$(id -u)" = 0 ]; then SUDO=""; elif have sudo; then SUDO=sudo; else die "--deb needs root or sudo"; fi
  step "Installing the .deb package (apt)..."
  cp "$TMP/$FILE" "$TMP/lightcode.deb"
  $SUDO apt-get install -y "$TMP/lightcode.deb"
  say ""
  say "LightCode $VERSION installed. Start it from your app menu or run:  lightcode"
  exit 0
fi

OPT="$HOME/.local/opt/lightcode"
BIN="$HOME/.local/bin"
step "Installing into $OPT ..."
mkdir -p "$OPT" "$BIN" "$HOME/.local/share/applications"
say "      Copying the AppImage..."
install -m 755 "$TMP/$FILE" "$OPT/LightCode.AppImage"
say "      Adding the 'lightcode' command and the app-menu entry..."

# The AppImage needs FUSE 2; without it, unpack-and-run still works. Ubuntu 24.04+ blocks the
# Chromium sandbox for AppImages (AppArmor), which needs --no-sandbox.
cat > "$BIN/lightcode" <<'LAUNCHER'
#!/bin/sh
APP="$HOME/.local/opt/lightcode/LightCode.AppImage"
if [ ! -e /dev/fuse ] || ! command -v fusermount >/dev/null 2>&1; then
  export APPIMAGE_EXTRACT_AND_RUN=1
fi
if [ "$(sysctl -n kernel.apparmor_restrict_unprivileged_userns 2>/dev/null)" = 1 ]; then
  exec "$APP" --no-sandbox "$@"
fi
exec "$APP" "$@"
LAUNCHER
chmod 755 "$BIN/lightcode"

ICON_DIR="$HOME/.local/share/icons/hicolor/180x180/apps"
mkdir -p "$ICON_DIR"
fetch "https://lightcode.live/apple-touch-icon.png" "$ICON_DIR/lightcode.png" 2>/dev/null || true
cat > "$HOME/.local/share/applications/lightcode.desktop" <<DESKTOP
[Desktop Entry]
Type=Application
Name=LightCode
Comment=One workspace for every AI coding agent
Exec=$BIN/lightcode %U
Icon=lightcode
Terminal=false
Categories=Development;
StartupWMClass=LightCode
MimeType=x-scheme-handler/lightcode;
DESKTOP
have update-desktop-database && update-desktop-database "$HOME/.local/share/applications" >/dev/null 2>&1 || true

say ""
say "LightCode $VERSION installed in $OPT"
case ":$PATH:" in
  *":$BIN:"*) say "Start it from your app menu or run:  lightcode" ;;
  *) say "Start it from your app menu, or add $BIN to your PATH and run:  lightcode" ;;
esac
say "LightCode updates itself in the background."
