#!/usr/bin/env bash
# Copyright (c) 2026 TOMOSE株式会社
# All rights reserved.
#
# empa CLI installer.
#
#   curl -fsSL https://cli.empa.jp/prd/stable/install.sh | bash
#
# Downloads the latest published empa CLI for your OS/arch from the public
# CloudFront distribution (cli.empa.jp), verifies its sha256 against the
# release checksums, and installs it onto your PATH. No GitHub / Homebrew
# access required.
#
# The distribution is laid out per environment AND per channel — every install
# / manifest / asset path is `cli.empa.jp/<env>/<channel>/...` (PRD is NOT
# special-cased; that uniformity is the point). This single script is published
# verbatim to each `<env>/<channel>/install.sh` path; the publisher rewrites the
# two DEFAULT_* lines below so each copy knows its own env (which CloudFront
# subtree to fetch from) and channel:
#
#   https://cli.empa.jp/prd/stable/install.sh      -> env=prd channel=stable
#   https://cli.empa.jp/dev/prerelease/install.sh  -> env=dev channel=prerelease
#
# Environment overrides:
#   EMPA_SERIES       empa | empa-dev | empa-stg   (default: empa)
#   EMPA_CHANNEL      stable | prerelease          (default: this copy's channel; stable falls back to prerelease)
#   EMPA_VERSION      pin an exact tag, e.g. v1.2.2 (default: channel's latest)
#   EMPA_INSTALL_DIR  install directory            (default: /usr/local/bin if writable, else ~/.local/bin)
#   EMPA_BASE_URL     distribution base            (default: https://cli.empa.jp/<env>)

set -euo pipefail

# DEFAULT_ENV / DEFAULT_CHANNEL are rewritten in place when this script is
# published to an `<env>/<channel>/install.sh` path (cli-release.yml /
# scripts/deploy-site.sh). The in-repo source defaults to prd/stable so a
# locally-run copy targets production. EMPA_BASE_URL / EMPA_CHANNEL still win.
DEFAULT_ENV="prd"
DEFAULT_CHANNEL="stable"

BASE_URL="${EMPA_BASE_URL:-https://cli.empa.jp/${DEFAULT_ENV}}"
SERIES="${EMPA_SERIES:-empa}"
CHANNEL="${EMPA_CHANNEL:-${DEFAULT_CHANNEL}}"

err() { printf 'error: %s\n' "$1" >&2; exit 1; }
info() { printf '%s\n' "$1" >&2; }

case "$SERIES" in
  empa|empa-dev|empa-stg) ;;
  *) err "EMPA_SERIES must be one of: empa, empa-dev, empa-stg (got: $SERIES)";;
esac

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

# --- detect OS / arch --------------------------------------------------------
os="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$os" in
  linux|darwin) ;;
  *) err "unsupported OS '$os' — Windows users: download the _windows_amd64.zip from $BASE_URL/releases/<version>/";;
esac
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64)  arch="amd64" ;;
  aarch64|arm64) arch="arm64" ;;
  *) err "unsupported architecture '$arch'";;
esac

# --- resolve version ---------------------------------------------------------
version="${EMPA_VERSION:-}"
if [ -z "$version" ]; then
  manifest="$(curl -fsSL --proto '=https' "$BASE_URL/$CHANNEL/latest.json" 2>/dev/null || true)"
  if [ -z "$manifest" ] && [ "$CHANNEL" = "stable" ]; then
    info "stable channel not available — falling back to prerelease"
    CHANNEL="prerelease"
    manifest="$(curl -fsSL --proto '=https' "$BASE_URL/$CHANNEL/latest.json")"
  fi
  [ -n "$manifest" ] || err "could not fetch $CHANNEL manifest from $BASE_URL"
  version="$(printf '%s' "$manifest" | grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"\([^"]*\)".*/\1/')"
fi
[ -n "$version" ] || err "could not resolve version"
ver_no_v="${version#v}"

asset="${SERIES}_${ver_no_v}_${os}_${arch}.tar.gz"
asset_url="$BASE_URL/releases/$version/$asset"
checksums_url="$BASE_URL/releases/$version/checksums.txt"

# --- download ----------------------------------------------------------------
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
info "Downloading $SERIES $version ($os/$arch) ..."
curl -fSL --proto '=https' -o "$tmp/$asset" "$asset_url" \
  || err "download failed: $asset_url"
curl -fSL --proto '=https' -o "$tmp/checksums.txt" "$checksums_url" \
  || err "download failed: $checksums_url"

# --- verify sha256 -----------------------------------------------------------
(
  cd "$tmp"
  if command -v sha256sum >/dev/null 2>&1; then
    grep " $asset\$" checksums.txt | sha256sum -c - >/dev/null \
      || err "checksum verification failed for $asset"
  elif command -v shasum >/dev/null 2>&1; then
    want="$(grep " $asset\$" checksums.txt | awk '{print $1}')"
    got="$(shasum -a 256 "$asset" | awk '{print $1}')"
    [ -n "$want" ] && [ "$want" = "$got" ] || err "checksum verification failed for $asset"
  else
    info "WARNING: no sha256 tool found — skipping checksum verification"
  fi
)
info "Checksum OK"

# --- extract & install -------------------------------------------------------
tar -xzf "$tmp/$asset" -C "$tmp"
[ -f "$tmp/$SERIES" ] || err "binary '$SERIES' not found in archive"

dir="${EMPA_INSTALL_DIR:-}"
if [ -z "$dir" ]; then
  if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
    dir="/usr/local/bin"
  else
    dir="$HOME/.local/bin"
  fi
fi
mkdir -p "$dir"
install -m 0755 "$tmp/$SERIES" "$dir/$SERIES" 2>/dev/null \
  || { cp "$tmp/$SERIES" "$dir/$SERIES" && chmod 0755 "$dir/$SERIES"; } \
  || err "failed to install into $dir"

info "Installed $SERIES $version -> $dir/$SERIES"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) info "NOTE: $dir is not on your PATH. Add it, e.g.: export PATH=\"$dir:\$PATH\"";;
esac
"$dir/$SERIES" version 2>/dev/null || true
