#!/bin/sh
# xcode installer for Termux (Android), Linux (x64, arm64) and macOS (Apple Silicon)
#   curl -fsSL https://xcode-cli.vercel.app/install.sh | bash
set -eu

BASE="${XCODE_UPDATE_URL:-https://xcode-cli.vercel.app}"
BASE="${BASE%/}"
INSTALL_DIR="${XCODE_INSTALL_DIR:-$HOME/.xcode/bin}"
EXE="$INSTALL_DIR/xcode"

step() { printf '  [%s/4] %s\n' "$1" "$2"; }
fail() { printf '\n  x %s\n\n' "$1" >&2; exit 1; }
dim() { printf '        %s\n' "$1"; }
warn() { printf '        ! %s\n' "$1"; }

if command -v curl >/dev/null 2>&1; then
  fetch_file() { curl -fsSL --retry 2 "$1" -o "$2"; }
  fetch_text() { curl -fsSL --retry 2 "$1"; }
elif command -v wget >/dev/null 2>&1; then
  fetch_file() { wget -qO "$2" "$1"; }
  fetch_text() { wget -qO- "$1"; }
else
  fail "curl or wget is required."
fi

# macOS ships shasum, Termux and most Linux ship sha256sum; openssl is the last resort.
sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | cut -d' ' -f1
  elif command -v openssl >/dev/null 2>&1; then
    openssl dgst -sha256 "$1" | sed 's/^.*= *//'
  else
    return 1
  fi
}

lower() { printf '%s' "$1" | tr 'A-F' 'a-f'; }

version=""
expected=""
# Reads /api/version once and keeps the release version plus the SHA-256 published for one platform.
release() {
  manifest=$(fetch_text "$BASE/api/version" 2>/dev/null) || fail "Could not reach $BASE/api/version"
  version=$(printf '%s' "$manifest" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)
  [ -n "$version" ] || fail "The release manifest reports no version."
  expected=$(printf '%s\n' "$manifest" \
    | sed -n '/"sha256"[[:space:]]*:/,/}/p' \
    | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([0-9a-fA-F]\{64\}\)\".*/\1/p" \
    | head -n 1)
  [ -n "$expected" ] || fail "Security Error: the release manifest has no SHA-256 for $1."
  dim "v$version"
}

# Verifies a downloaded archive against the manifest and exits on any mismatch.
verify() {
  actual=$(sha256_of "$1") || {
    rm -f "$1"
    fail "No SHA-256 tool found (need sha256sum, shasum or openssl)."
  }
  if [ "$(lower "$actual")" != "$(lower "$expected")" ]; then
    rm -f "$1"
    fail "Checksum mismatch, the download is corrupt or tampered. Please run the installer again."
  fi
  dim "checksum verified (SHA-256)"
}

# ---------------------------------------------------------------------------------------
# 1. Termux on Android.
# The published linux-arm64 build is a glibc binary and Android has no /lib/ld-linux-aarch64.so.1, so it is stored
# as $HOME/.xcode/bin/xcode-bin and started by a launcher at $HOME/.xcode/bin/xcode that runs Termux's glibc loader.
# The launcher also drops Termux's bionic LD_PRELOAD (fatal to that loader and to clone/statx) and, on Android
# 10/11, preloads a seccomp shim for syscalls the app sandbox traps. packages/cli/src/util/process.ts depends on
# exactly these paths, so every child process and `xcode upgrade` restart through the launcher.
# Approach from https://github.com/HanSoBored/opencode-termux (MIT).
if [ -n "${TERMUX_VERSION:-}" ] || [ -d /data/data/com.termux ]; then
  prefix="${PREFIX:-/data/data/com.termux/files/usr}"
  termux_home="${HOME:-/data/data/com.termux/files/home}"
  dir="$termux_home/.xcode"
  INSTALL_DIR="$dir/bin"
  machine=$(uname -m 2>/dev/null || echo unknown)
  case "$machine" in
    aarch64 | arm64) ;;
    *) fail "xcode needs a 64-bit ARM (aarch64) device; this one is $machine." ;;
  esac

  printf '\n  \033[36m◆ xcode\033[0m  \033[90mAI coding agent for your terminal\033[0m\n'
  printf '\033[90m        Termux on Android %s · linux-arm64\033[0m\n\n' "$machine"

  find_loader() {
    for candidate in "$prefix/glibc/lib/ld-linux-aarch64.so.1" "$prefix/glibc/bin/ld.so"; do
      if [ -x "$candidate" ]; then
        printf '%s' "$candidate"
        return 0
      fi
    done
    return 1
  }

  step 1 "Checking Termux packages (glibc loader, curl, tar)..."
  if command -v pkg >/dev/null 2>&1; then
    command -v curl >/dev/null 2>&1 || pkg install -y curl >/dev/null 2>&1 || true
    command -v tar >/dev/null 2>&1 || pkg install -y tar >/dev/null 2>&1 || true
    if [ ! -f "$prefix/etc/tls/cert.pem" ] && [ ! -f "$prefix/etc/ssl/certs/ca-certificates.crt" ]; then
      pkg install -y ca-certificates >/dev/null 2>&1 || true
    fi
  fi
  command -v curl >/dev/null 2>&1 || command -v wget >/dev/null 2>&1 || fail "curl or wget is required."
  command -v tar >/dev/null 2>&1 || fail "tar is required."
  [ -x "$prefix/bin/bash" ] || fail "Termux bash not found. Run: pkg install bash"

  loader=$(find_loader || true)
  if [ -z "$loader" ]; then
    dim "Installing the Termux glibc runtime (the release is a glibc build)"
    if command -v pkg >/dev/null 2>&1; then
      pkg install -y glibc-repo >/dev/null 2>&1 || fail "Could not install glibc-repo. Run: pkg install glibc-repo"
      pkg update -y >/dev/null 2>&1 || true
      pkg install -y glibc-runner >/dev/null 2>&1 || pkg install -y glibc >/dev/null 2>&1 || true
    fi
    loader=$(find_loader || true)
  fi
  [ -n "$loader" ] || fail "Termux glibc loader not found. Run: pkg install glibc-repo; pkg update; pkg install glibc-runner"
  dim "glibc loader: $loader"

  step 2 "Checking the latest release for linux-arm64..."
  release "linux-arm64"

  step 3 "Downloading linux-arm64..."
  archive="${TMPDIR:-$prefix/tmp}/xcode-$version-linux-arm64.tar.gz"
  fetch_file "$BASE/xcode-linux-arm64.tar.gz" "$archive" || fail "Download failed: $BASE/xcode-linux-arm64.tar.gz"
  verify "$archive"

  unpack=$(mktemp -d 2>/dev/null || printf '%s' "${TMPDIR:-$prefix/tmp}/xcode-unpack-$$")
  mkdir -p "$unpack"
  tar -xzf "$archive" -C "$unpack" || {
    rm -rf "$unpack" "$archive"
    fail "The archive could not be extracted."
  }
  [ -f "$unpack/xcode" ] || {
    rm -rf "$unpack" "$archive"
    fail "The archive does not contain xcode."
  }
  # Leftovers of the old source-bundle installer (xcode.tgz plus a node tree).
  rm -rf "$dir/packages" "$dir/node_modules" "$dir/package.json" "$dir/bun.lock"
  mkdir -p "$INSTALL_DIR" "$dir/lib"
  chmod +x "$unpack/xcode"
  rm -f "$INSTALL_DIR/xcode-bin.old"
  if [ -f "$INSTALL_DIR/xcode-bin" ]; then
    mv -f "$INSTALL_DIR/xcode-bin" "$INSTALL_DIR/xcode-bin.old" 2>/dev/null || true
  fi
  mv -f "$unpack/xcode" "$INSTALL_DIR/xcode-bin"
  chmod 755 "$INSTALL_DIR/xcode-bin"
  rm -f "$INSTALL_DIR/xcode-bin.old"
  rm -rf "$unpack" "$archive"

  sdk=$(getprop ro.build.version.sdk 2>/dev/null || echo 99)
  case "$sdk" in '' | *[!0-9]*) sdk=99 ;; esac
  if [ "$sdk" -lt 31 ]; then
    dim "Android SDK $sdk: building the seccomp shim (needs clang)"
    command -v clang >/dev/null 2>&1 || pkg install -y clang >/dev/null 2>&1 || true
    if command -v clang >/dev/null 2>&1 \
      && fetch_file "$BASE/termux/libseccomp-shim.c" "$dir/lib/libseccomp-shim.c" 2>/dev/null \
      && clang --target=aarch64-linux-gnu --sysroot="$prefix/glibc" -shared -fPIC -O2 -nostdlib \
        -o "$dir/lib/libseccomp-shim.so" "$dir/lib/libseccomp-shim.c" >/dev/null 2>&1; then
      dim "seccomp shim built"
    else
      rm -f "$dir/lib/libseccomp-shim.so"
      warn "Could not build the seccomp shim; on Android 10/11 xcode may fail to start."
      warn "Fix: pkg install clang, then run this installer again."
    fi
  else
    rm -f "$dir/lib/libseccomp-shim.so"
  fi

  step 4 "Writing the launcher at $INSTALL_DIR/xcode"
  # Written next to the real path and renamed into place: `xcode upgrade` runs this installer while the old launcher
  # is still executing the upgrade, and bash reads its own script file as it goes.
  # Android has no /usr/bin/env; the glibc process must be able to exec this without termux-exec.
  cat >"$INSTALL_DIR/xcode.new" <<LAUNCHER
#!$prefix/bin/bash
# xcode launcher for Termux, written by $BASE/install.sh.
# Contract: packages/cli/src/util/process.ts in https://github.com/antony854908/xcode
export XCODE_LAUNCHER="$INSTALL_DIR/xcode"
export XCODE_BINARY="$INSTALL_DIR/xcode-bin"
export BUN_SELF_EXE="$INSTALL_DIR/xcode-bin"
# termux-exec injects a bionic LD_PRELOAD the glibc loader cannot read; xcode restores the original value for the
# commands it runs, so bionic children never inherit the shim.
export XCODE_CHILD_LD_PRELOAD="\${XCODE_CHILD_LD_PRELOAD:-\${LD_PRELOAD:-}}"
unset LD_PRELOAD
unset LD_LIBRARY_PATH
if [ -f "$dir/lib/libseccomp-shim.so" ]; then
  export LD_PRELOAD="$dir/lib/libseccomp-shim.so"
fi

# Termux keeps its CA bundle in a few possible places; the glibc build looks at SSL_CERT_FILE.
if [ -z "\${SSL_CERT_FILE:-}" ]; then
  for cert_file in "$prefix/etc/tls/cert.pem" "$prefix/etc/ssl/certs/ca-certificates.crt" "$prefix/glibc/etc/ssl/certs/ca-certificates.crt"; do
    if [ -f "\$cert_file" ]; then
      export SSL_CERT_FILE="\$cert_file"
      break
    fi
  done
fi

# Resolve the glibc loader again at runtime: a Termux upgrade can move or reinstall it.
GLIBC_LOADER=""
for candidate in "$prefix/glibc/bin/ld.so" "$prefix/glibc/lib/ld-linux-aarch64.so.1"; do
  if [ -x "\$candidate" ]; then
    GLIBC_LOADER="\$candidate"
    break
  fi
done
if [ -z "\$GLIBC_LOADER" ]; then
  printf '\n  xcode cannot start: the Termux glibc loader is missing.\n' >&2
  printf '  Fix: pkg install glibc-repo; pkg update; pkg install glibc-runner\n\n' >&2
  exit 1
fi

exec "\$GLIBC_LOADER" "$INSTALL_DIR/xcode-bin" "\$@"
LAUNCHER
  chmod 755 "$INSTALL_DIR/xcode.new"
  mv -f "$INSTALL_DIR/xcode.new" "$INSTALL_DIR/xcode"
  # $PREFIX/bin is always on PATH in Termux, and this also replaces an old install that dropped the raw binary there
  # (Android kills it with "cannot execute: required file not found" because that binary needs a glibc loader).
  rm -f "$prefix/bin/xcode"
  ln -s "$INSTALL_DIR/xcode" "$prefix/bin/xcode" || fail "Could not link $prefix/bin/xcode"
  dim "xcode -> $prefix/bin/xcode"

  installed=$("$INSTALL_DIR/xcode" --version 2>&1) || fail "xcode failed to start: $installed"
  printf '\n  \033[32m✓ %s installed on Termux\033[0m\n\n' "$installed"
  printf '    \033[36mxcode\033[0m                 start in the current folder\n'
  printf '    \033[36mxcode -p "..."\033[0m         one-shot answer, no UI\n'
  printf '    \033[36mxcode upgrade\033[0m         update (also automatic)\n'
  printf '\n'

  printf '  \033[36mTip:\033[0m make the TUI usable on a phone keyboard — add to ~/.termux/termux.properties:\n'
  printf '       %s\n\n' "extra-keys = [['ESC','TAB','CTRL','ALT','UP','DOWN','LEFT','RIGHT']]"
  if [ "$sdk" -lt 31 ]; then
    printf '  \033[33mNote:\033[0m Android 10/11 without the seccomp shim may fail; run the installer again after pkg install clang.\n\n'
  else
    printf '  \033[33mTip:\033[0m run termux-wake-lock so Android does not kill long tasks in the background.\n\n'
  fi
  exit 0
fi

# ---------------------------------------------------------------------------------------
# 2. Linux, macOS and Windows (Git Bash).
os=$(uname -s 2>/dev/null || echo unknown)
machine=$(uname -m 2>/dev/null || echo unknown)

case "$os" in
  Linux)
    case "$machine" in
      x86_64 | amd64) platform="linux-x64" ;;
      aarch64 | arm64) platform="linux-arm64" ;;
      *) fail "unsupported CPU on Linux: $machine. Build from source: https://github.com/antony854908/xcode" ;;
    esac
    ;;
  Darwin)
    case "$machine" in
      arm64) platform="darwin-arm64" ;;
      *) fail "macOS builds ship for Apple Silicon (arm64) only. Intel Macs can build from source: https://github.com/antony854908/xcode" ;;
    esac
    ;;
  *) fail "unsupported system: $os. On Windows use: irm https://xcode-cli.vercel.app/install.ps1 | iex" ;;
esac

printf '\n  \033[36m◆ xcode\033[0m  \033[90mAI coding agent for your terminal\033[0m\n'
printf '\033[90m        %s %s · %s\033[0m\n\n' "$os" "$machine" "$platform"

step 1 "Checking the latest release..."
release "$platform"

step 2 "Downloading $platform..."
archive="${TMPDIR:-/tmp}/xcode-$version-$platform.tar.gz"
fetch_file "$BASE/xcode-$platform.tar.gz" "$archive" || fail "Download failed: $BASE/xcode-$platform.tar.gz"
verify "$archive"

step 3 "Installing to $INSTALL_DIR"
mkdir -p "$INSTALL_DIR"
if [ -f "$EXE" ]; then
  old="$EXE.old"
  rm -f "$old"
  if [ -e "$old" ]; then
    old="$EXE.$(date +%Y%m%d%H%M%S).old"
  fi
  mv "$EXE" "$old" 2>/dev/null || true
fi
unpack=$(mktemp -d 2>/dev/null || printf '%s' "${TMPDIR:-/tmp}/xcode-unpack-$$")
mkdir -p "$unpack"
tar -xzf "$archive" -C "$unpack" || {
  rm -rf "$unpack" "$archive"
  fail "The archive could not be extracted."
}
[ -f "$unpack/xcode" ] || {
  rm -rf "$unpack" "$archive"
  fail "The archive does not contain xcode."
}
chmod +x "$unpack/xcode"
mv "$unpack/xcode" "$EXE"
rm -rf "$unpack" "$archive"

step 4 "Adding xcode to your PATH"
line="export PATH=\"$INSTALL_DIR:\$PATH\""
added=""
for rc in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.profile"; do
  [ -e "$rc" ] || continue
  if grep -Fq "$INSTALL_DIR" "$rc" 2>/dev/null; then
    added="already there"
    break
  fi
done
if [ -z "$added" ]; then
  rc="$HOME/.zshrc"
  if [ "$(basename "${SHELL:-sh}")" = "bash" ]; then
    rc="$HOME/.bashrc"
  fi
  [ -e "$rc" ] || rc="$HOME/.profile"
  {
    printf '\n# xcode\n%s\n' "$line"
  } >>"$rc"
  added="added to $rc (new terminals pick it up)"
fi
dim "$added"

installed=$("$EXE" --version 2>&1) || {
  warn "xcode was installed at $EXE but does not start:"
  warn "$installed"
  warn "A glibc mismatch looks like this; run the installer through Termux (Android) or check your libc."
  exit 1
}
printf '\n  \033[32m✓ %s installed\033[0m\n\n' "$installed"
printf '    \033[36mxcode\033[0m                 start in the current folder\n'
printf '    \033[36mxcode -p "..."\033[0m         one-shot answer, no UI\n'
printf '    \033[36m/login  /account\033[0m      sign in, switch accounts\n'
printf '    \033[36mxcode upgrade\033[0m         update (also automatic)\n'
printf '\n'
