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

dir="${AIC_INSTALL_DIR:-$HOME/.aicockpit/bin}"
version="${AIC_VERSION:-}"
version="${version#v}"
releases="${AIC_RELEASES_URL:-https://aicockpit.ai/cli/releases}"
modify=true

usage() {
  cat <<'EOF'
AI Cockpit CLI installer

Usage: install.sh [options]

Options:
  -h, --help                Show this help
  -v, --version <version>   Install a specific release
      --install-dir <path>  Install into this directory
      --no-modify-path      Do not update the shell profile

Environment:
  AIC_VERSION               Version to install
  AIC_INSTALL_DIR           Installation directory
  AIC_RELEASES_URL          Base URL containing versioned releases
EOF
}

fail() {
  printf 'AI Cockpit installer: %s\n' "$*" >&2
  exit 1
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    -h | --help)
      usage
      exit 0
      ;;
    -v | --version)
      [[ -n "${2:-}" ]] || fail "$1 requires a version"
      version="${2#v}"
      shift 2
      ;;
    --install-dir)
      [[ -n "${2:-}" ]] || fail "$1 requires a path"
      dir="$2"
      shift 2
      ;;
    --no-modify-path)
      modify=false
      shift
      ;;
    *)
      fail "unknown option: $1"
      ;;
  esac
done

command -v curl >/dev/null 2>&1 || fail "curl is required"

raw="$(uname -s)"
case "$raw" in
  Darwin*) os=darwin ;;
  Linux*) os=linux ;;
  MINGW* | MSYS* | CYGWIN*) os=windows ;;
  *) fail "unsupported operating system: $raw" ;;
esac

arch="$(uname -m)"
case "$arch" in
  arm64 | aarch64) arch=arm64 ;;
  x86_64 | amd64) arch=x64 ;;
  *) fail "unsupported architecture: $arch" ;;
esac

if [[ "$os" == darwin && "$arch" == x64 ]]; then
  translated="$(sysctl -n sysctl.proc_translated 2>/dev/null || printf '0')"
  [[ "$translated" != 1 ]] || arch=arm64
fi

target="$os-$arch"
if [[ "$arch" == x64 ]]; then
  baseline=false
  if [[ "$os" == linux ]] && ! grep -qwi avx2 /proc/cpuinfo 2>/dev/null; then
    baseline=true
  fi
  if [[ "$os" == darwin && "$(sysctl -n hw.optional.avx2_0 2>/dev/null || printf '0')" != 1 ]]; then
    baseline=true
  fi
  [[ "$baseline" != true ]] || target="$target-baseline"
fi

if [[ "$os" == linux ]]; then
  musl=false
  [[ ! -f /etc/alpine-release ]] || musl=true
  if command -v ldd >/dev/null 2>&1 && ldd --version 2>&1 | grep -qi musl; then
    musl=true
  fi
  [[ "$musl" != true ]] || target="$target-musl"
fi

target="${AIC_TARGET:-$target}"
case "$target" in
  linux-*) ext=tar.gz ;;
  darwin-* | windows-*) ext=zip ;;
  *) fail "unsupported target: $target" ;;
esac

archive="aic-$target.$ext"
if [[ -n "${AIC_RELEASE_BASE_URL:-}" ]]; then
  base="${AIC_RELEASE_BASE_URL%/}"
elif [[ -n "$version" ]]; then
  base="${releases%/}/v$version"
else
  base="${releases%/}/latest"
fi

fetch() {
  local url="$1"
  local out="$2"
  if [[ "$url" == https://* ]]; then
    curl --proto '=https' --tlsv1.2 --fail --silent --show-error --location --retry 3 "$url" --output "$out"
    return
  fi
  [[ "${AIC_ALLOW_INSECURE:-}" == 1 ]] || fail "refusing non-HTTPS URL: $url"
  curl --fail --silent --show-error --location --retry 3 "$url" --output "$out"
}

digest() {
  local file="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" | awk '{ print $1 }'
    return
  fi
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" | awk '{ print $1 }'
    return
  fi
  if command -v openssl >/dev/null 2>&1; then
    openssl dgst -sha256 "$file" | awk '{ print $NF }'
    return
  fi
  fail "sha256sum, shasum, or openssl is required"
}

tmp="$(mktemp -d "${TMPDIR:-/tmp}/aic-install.XXXXXX")"
trap 'rm -rf "$tmp"' EXIT
payload="$tmp/$archive"
sums="$tmp/SHA256SUMS"
extract="$tmp/extract"
mkdir -p "$extract"

printf 'Downloading AI Cockpit CLI %s (%s)...\n' "${version:-latest}" "$target"
fetch "$base/$archive" "$payload"
fetch "$base/SHA256SUMS" "$sums"

expected="$(awk -v file="$archive" '$2 == file || $2 == "*" file { print $1; exit }' "$sums")"
[[ -n "$expected" ]] || fail "SHA256SUMS does not contain $archive"
actual="$(digest "$payload")"
expected="$(printf '%s' "$expected" | tr '[:upper:]' '[:lower:]')"
actual="$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')"
[[ "$actual" == "$expected" ]] || fail "checksum mismatch for $archive"

if [[ "$ext" == tar.gz ]]; then
  command -v tar >/dev/null 2>&1 || fail "tar is required"
  tar -xzf "$payload" -C "$extract"
else
  command -v unzip >/dev/null 2>&1 || fail "unzip is required"
  unzip -q "$payload" -d "$extract"
fi

exe=aic
[[ "$target" != windows-* ]] || exe=aic.exe
binary="$extract/$exe"
[[ -f "$binary" ]] || fail "$archive does not contain $exe"
chmod 755 "$binary"

if [[ "$target" == darwin-* ]]; then
  trusted=false
  if command -v codesign >/dev/null 2>&1 && command -v spctl >/dev/null 2>&1 && \
    codesign --verify --deep --strict "$binary" >/dev/null 2>&1 && \
    spctl --assess --type execute "$binary" >/dev/null 2>&1; then
    trusted=true
  fi
  if [[ "$trusted" == true ]]; then
    printf 'Verified macOS Developer ID signature and notarization.\n'
  fi
  if [[ "$trusted" != true ]]; then
    printf '\nWarning: the macOS signature or notarization could not be verified.\n' >&2
    printf 'The CLI will be installed, but Gatekeeper may block it. Prefer a signed release when available.\n' >&2
  fi
fi

mkdir -p "$dir"
cp -R "$extract/." "$dir/"
chmod 755 "$dir/$exe"
if [[ "$target" != windows-* ]]; then
  ln -sfn "$exe" "$dir/aicockpit"
fi

profile=""
line=""
shell="$(basename "${SHELL:-sh}")"
case "$shell" in
  zsh)
    profile="${ZDOTDIR:-$HOME}/.zshrc"
    line="export PATH=\"$dir:\$PATH\""
    ;;
  bash)
    profile="$HOME/.bashrc"
    line="export PATH=\"$dir:\$PATH\""
    ;;
  fish)
    profile="$HOME/.config/fish/config.fish"
    line="fish_add_path \"$dir\""
    ;;
  *)
    profile="$HOME/.profile"
    line="export PATH=\"$dir:\$PATH\""
    ;;
esac

if [[ "$modify" == true && ":$PATH:" != *":$dir:"* ]]; then
  mkdir -p "$(dirname "$profile")"
  touch "$profile"
  if ! grep -Fqx "$line" "$profile"; then
    printf '\n# AI Cockpit CLI\n%s\n' "$line" >>"$profile"
  fi
fi

"$dir/$exe" --version
printf '\nAI Cockpit CLI installed at %s\n' "$dir/$exe"
if [[ ":$PATH:" != *":$dir:"* ]]; then
  printf 'Open a new terminal or run: export PATH="%s:$PATH"\n' "$dir"
fi
printf 'Start the TUI with: aic\n'
