#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2026 Stag Language Contributors
#
# Stag Toolchain Auto-Installer for Linux (x64, arm64) and macOS (arm64).
# Detects OS and CPU architecture, queries the latest GitHub Release of
# stag-lang/stag, verifies SHA-256 checksums, and installs stagc + stag-lsp.
#
# Usage:
#   curl -fsSL https://stag-lang.github.io/install.sh | bash
#   curl -fsSL https://stag-lang.github.io/install.sh | bash -s -- --yes --prefix="$HOME/.local"
#
# Options:
#   --version <vX.Y.Z>   Install a specific release tag instead of latest
#   --prefix <dir>       Installation prefix (default: $HOME/.local)
#   --yes, -y            Non-interactive mode (accept defaults)
#   --cli                Force terminal installer on Linux (skip GTK3 GUI)
#   --no-lsp             Install stagc only (skip stag-lsp)
#   --with-lsp           Install both stagc and stag-lsp (default)
#   --no-path            Do not modify shell profile PATH
#   -h, --help           Show this help message

set -euo pipefail

REPO="stag-lang/stag"
API_LATEST="https://api.github.com/repos/${REPO}/releases/latest"

REQ_VERSION=""
PREFIX="${HOME}/.local"
AUTO_YES=0
FORCE_CLI=0
INSTALL_LSP=1
UPDATE_PATH=1

usage() {
  cat <<'EOF'
Stag Toolchain Installer (Linux & macOS)

Usage:
  curl -fsSL https://stag-lang.github.io/install.sh | bash
  curl -fsSL https://stag-lang.github.io/install.sh | bash -s -- [options]

Options:
  --version <vX.Y.Z>   Install a specific release tag (default: latest)
  --prefix <dir>       Installation prefix (default: ~/.local)
  --yes, -y            Non-interactive installation with default options
  --cli                Use terminal installer on Linux (disable GUI)
  --no-lsp             Skip installing stag-lsp
  --with-lsp           Install stag-lsp (default)
  --no-path            Do not modify shell startup files
  -h, --help           Display this help text
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --version)
      REQ_VERSION="${2:?--version requires a tag such as v0.1.0}"
      shift 2
      ;;
    --version=*)
      REQ_VERSION="${1#*=}"
      shift
      ;;
    --prefix)
      PREFIX="${2:?--prefix requires a directory path}"
      shift 2
      ;;
    --prefix=*)
      PREFIX="${1#*=}"
      shift
      ;;
    --yes|-y)
      AUTO_YES=1
      shift
      ;;
    --cli)
      FORCE_CLI=1
      shift
      ;;
    --no-lsp)
      INSTALL_LSP=0
      shift
      ;;
    --with-lsp)
      INSTALL_LSP=1
      shift
      ;;
    --no-path)
      UPDATE_PATH=0
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      printf 'Error: unknown option: %s\n' "$1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

log() {
  printf '[stag-install] %s\n' "$*"
}

die() {
  printf '[stag-install] Error: %s\n' "$*" >&2
  exit 1
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || die "required command '$1' not found in PATH"
}

fetch_to_file() {
  local url="$1"
  local dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --retry 3 --retry-delay 1 -o "${dest}" "${url}"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "${dest}" "${url}"
  else
    die "either 'curl' or 'wget' is required to download release artifacts"
  fi
}

fetch_text() {
  local url="$1"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -H "Accept: application/vnd.github+json" "${url}"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO- --header="Accept: application/vnd.github+json" "${url}"
  else
    die "either 'curl' or 'wget' is required"
  fi
}

sha256_file() {
  local f="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "${f}" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "${f}" | awk '{print $1}'
  elif command -v openssl >/dev/null 2>&1; then
    openssl dgst -sha256 "${f}" | awk '{print $NF}'
  else
    die "no SHA-256 tool found (need sha256sum, shasum, or openssl)"
  fi
}

verify_checksum() {
  local asset_name="$1"
  local file_path="$2"
  local sums_path="$3"

  local expected
  expected="$(awk -v name="${asset_name}" '$2 == name || $2 == ("*" name) {print $1; exit}' "${sums_path}")"
  if [[ -z "${expected}" ]]; then
    die "checksum entry for '${asset_name}' not found in SHA256SUMS.txt"
  fi

  local actual
  actual="$(sha256_file "${file_path}")"
  if [[ "${actual}" != "${expected}" ]]; then
    die "SHA-256 verification failed for ${asset_name} (expected ${expected}, got ${actual})"
  fi
  log "SHA-256 verified: ${asset_name}"
}

detect_platform() {
  local raw_os raw_arch
  raw_os="$(uname -s)"
  raw_arch="$(uname -m)"

  case "${raw_os}" in
    Linux)  OS="linux" ;;
    Darwin) OS="macos" ;;
    *)
      die "unsupported operating system '${raw_os}'. On Windows, download stag-setup-*-windows-x64.exe from https://github.com/${REPO}/releases"
      ;;
  esac

  case "${raw_arch}" in
    x86_64|amd64)  ARCH="x64" ;;
    aarch64|arm64) ARCH="arm64" ;;
    *)
      die "unsupported CPU architecture '${raw_arch}'. Supported targets: linux-x64, linux-arm64, macos-arm64."
      ;;
  esac

  if [[ "${OS}" == "macos" && "${ARCH}" != "arm64" ]]; then
    die "prebuilt macOS binaries currently target Apple Silicon (arm64). Intel macOS users can build from source: https://github.com/${REPO}#build-from-source"
  fi
}

resolve_version() {
  if [[ -n "${REQ_VERSION}" ]]; then
    TAG="${REQ_VERSION}"
    [[ "${TAG}" == v* ]] || TAG="v${TAG}"
    VERSION="${TAG#v}"
    return
  fi

  log "Querying latest release from GitHub (${REPO})..."
  local json
  json="$(fetch_text "${API_LATEST}")" || die "failed to query ${API_LATEST}"
  TAG="$(printf '%s\n' "${json}" | sed -n 's/.*"tag_name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n 1)"
  if [[ -z "${TAG}" ]]; then
    die "could not determine latest release tag from GitHub API response"
  fi
  VERSION="${TAG#v}"
}

update_shell_profiles() {
  local bin_dir="$1"
  local marker="# Stag toolchain PATH"
  local line="export PATH=\"${bin_dir}:\$PATH\""
  local profiles=("${HOME}/.zshrc" "${HOME}/.bashrc" "${HOME}/.profile")
  if [[ "${OS}" == "macos" ]]; then
    profiles+=("${HOME}/.bash_profile")
  fi

  local updated=0
  for prof in "${profiles[@]}"; do
    if [[ -f "${prof}" ]] || [[ "${OS}" == "macos" && "${prof}" == "${HOME}/.zshrc" ]] || [[ "${OS}" == "linux" && "${prof}" == "${HOME}/.bashrc" ]]; then
      if [[ -f "${prof}" ]] && grep -Fq "${bin_dir}" "${prof}"; then
        continue
      fi
      {
        printf '\n%s\n%s\n' "${marker}" "${line}"
      } >> "${prof}"
      log "Added ${bin_dir} to ${prof}"
      updated=1
    fi
  done
  if [[ "${updated}" -eq 1 ]]; then
    log "Restart your shell or run: export PATH=\"${bin_dir}:\$PATH\""
  fi
}

install_macos() {
  local asset="stag-${VERSION}-macos-${ARCH}.tar.gz"
  local base_url="https://github.com/${REPO}/releases/download/${TAG}"
  local tarball="${TMPDIR_STAG}/${asset}"
  local sums="${TMPDIR_STAG}/SHA256SUMS.txt"

  log "Downloading ${asset} and SHA256SUMS.txt..."
  fetch_to_file "${base_url}/${asset}" "${tarball}"
  fetch_to_file "${base_url}/SHA256SUMS.txt" "${sums}"
  verify_checksum "${asset}" "${tarball}" "${sums}"

  if [[ "${AUTO_YES}" -eq 0 && -r /dev/tty ]]; then
    local ans=""
    printf 'Install prefix [%s]: ' "${PREFIX}" > /dev/tty
    IFS= read -r ans < /dev/tty || true
    [[ -n "${ans}" ]] && PREFIX="${ans}"

    printf 'Install Stag Language Server (stag-lsp) for IDE support? [Y/n]: ' > /dev/tty
    IFS= read -r ans < /dev/tty || true
    case "${ans}" in
      n|N|no|NO) INSTALL_LSP=0 ;;
    esac

    printf 'Add %s/bin to shell PATH? [Y/n]: ' "${PREFIX}" > /dev/tty
    IFS= read -r ans < /dev/tty || true
    case "${ans}" in
      n|N|no|NO) UPDATE_PATH=0 ;;
    esac
  fi

  tar -xzf "${tarball}" -C "${TMPDIR_STAG}"
  local unpacked="${TMPDIR_STAG}/stag-${VERSION}-macos-${ARCH}"
  [[ -d "${unpacked}/bin" ]] || die "unexpected archive structure in ${asset}"

  mkdir -p "${PREFIX}/bin" "${PREFIX}/share/stag"
  cp -f "${unpacked}/bin/stagc" "${PREFIX}/bin/stagc"
  chmod 755 "${PREFIX}/bin/stagc"

  if [[ "${INSTALL_LSP}" -eq 1 && -f "${unpacked}/bin/stag-lsp" ]]; then
    cp -f "${unpacked}/bin/stag-lsp" "${PREFIX}/bin/stag-lsp"
    chmod 755 "${PREFIX}/bin/stag-lsp"
  fi

  if [[ -d "${unpacked}/lib" ]]; then
    mkdir -p "${PREFIX}/lib"
    cp -f "${unpacked}/lib/"* "${PREFIX}/lib/"
  fi

  [[ -f "${unpacked}/LICENSE" ]] && cp -f "${unpacked}/LICENSE" "${PREFIX}/share/stag/LICENSE"
  printf '%s\n' "${VERSION}" > "${PREFIX}/share/stag/VERSION"

  if [[ "${UPDATE_PATH}" -eq 1 ]]; then
    update_shell_profiles "${PREFIX}/bin"
  fi

  log "Installed Stag ${VERSION} to ${PREFIX}"
  "${PREFIX}/bin/stagc" --version
  if [[ "${INSTALL_LSP}" -eq 1 && -x "${PREFIX}/bin/stag-lsp" ]]; then
    "${PREFIX}/bin/stag-lsp" --version
  fi
}

install_linux() {
  local asset="stag-setup-${VERSION}-linux-${ARCH}"
  local base_url="https://github.com/${REPO}/releases/download/${TAG}"
  local installer="${TMPDIR_STAG}/${asset}"
  local sums="${TMPDIR_STAG}/SHA256SUMS.txt"

  log "Downloading ${asset} and SHA256SUMS.txt..."
  fetch_to_file "${base_url}/${asset}" "${installer}"
  fetch_to_file "${base_url}/SHA256SUMS.txt" "${sums}"
  verify_checksum "${asset}" "${installer}" "${sums}"

  chmod 755 "${installer}"

  local args=()
  [[ "${FORCE_CLI}" -eq 1 ]] && args+=(--cli)
  [[ "${AUTO_YES}" -eq 1 ]] && args+=(--yes)
  [[ "${UPDATE_PATH}" -eq 0 ]] && args+=(--no-path)
  if [[ "${INSTALL_LSP}" -eq 0 ]]; then
    args+=(--no-lsp)
  else
    args+=(--with-lsp)
  fi
  args+=("--prefix=${PREFIX}")

  log "Launching Stag ${VERSION} Linux installer..."
  if [[ "${AUTO_YES}" -eq 0 && ! -t 0 && -r /dev/tty ]]; then
    "${installer}" "${args[@]}" < /dev/tty
  elif [[ "${AUTO_YES}" -eq 0 && ! -t 0 && ! -r /dev/tty ]]; then
    "${installer}" --yes "${args[@]}"
  else
    "${installer}" "${args[@]}"
  fi
}

main() {
  detect_platform
  resolve_version
  log "Detected platform: ${OS}-${ARCH} | Target release: ${TAG}"

  TMPDIR_STAG="$(mktemp -d)"
  trap 'rm -rf "${TMPDIR_STAG}"' EXIT

  if [[ "${OS}" == "linux" ]]; then
    install_linux
  else
    install_macos
  fi
}

main
