#!/usr/bin/env bash
# Install the gog CLI AND the gog-* Claude skills on macOS.
#
#   gog:    already on PATH -> skip; else Homebrew; else the verified gog release
#           tarball -> ~/.local/bin (no sudo)
#   skills: symlink each skills/gog-<service>/ into ~/.claude/skills
#
# (Linux: ./install-linux.sh   Windows: install.ps1)
#
#   ./install-macos.sh                 # install gog (if missing) + link skills
#   ./install-macos.sh --skills-only   # link skills only (you manage gog yourself)
#   ./install-macos.sh --gog-only      # install/refresh gog only
#   ./install-macos.sh --force         # force-reinstall gog, then link skills
#   GOG_BIN_DIR=~/bin GOG_VERSION=0.23.0 CLAUDE_SKILLS_DIR=... ./install-macos.sh
set -euo pipefail

REPO="openclaw/gogcli"
OS_NAME="darwin"
FORCE=0; SKILLS_ONLY=0; GOG_ONLY=0

usage() { sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'; }
for a in "$@"; do
  case "$a" in
    --force)       FORCE=1 ;;
    --skills-only) SKILLS_ONLY=1 ;;
    --gog-only)    GOG_ONLY=1 ;;
    -h|--help)     usage; exit 0 ;;
    *) echo "error: unknown option '$a' (try --help)" >&2; exit 2 ;;
  esac
done

if [ "$(uname -s)" != "Darwin" ]; then
  echo "error: this is the macOS installer; OS is '$(uname -s)'." >&2
  [ "$(uname -s)" = "Linux" ] && echo "       On Linux run: ./install-linux.sh" >&2
  exit 1
fi

REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
have() { command -v "$1" >/dev/null 2>&1; }

GOG_TMP=""
_cleanup() { [ -n "$GOG_TMP" ] && { rm -f "$GOG_TMP"/* 2>/dev/null || true; rmdir "$GOG_TMP" 2>/dev/null || true; }; }
trap _cleanup EXIT

install_gog() {
  if have gog && [ "$FORCE" -ne 1 ]; then
    echo "gog already installed: $(gog --version 2>/dev/null)  ($(command -v gog))"
    return
  fi
  if have brew; then
    echo "Homebrew detected -> installing gog via openclaw/tap..."
    if brew list --formula gogcli >/dev/null 2>&1; then
      brew upgrade openclaw/tap/gogcli
    else
      brew install openclaw/tap/gogcli
    fi
    echo "gog: $(gog --version)"
    return
  fi

  echo "Homebrew not found -> installing the verified gog release..."
  local t ARCH BIN_DIR base asset expected actual
  for t in curl tar shasum; do
    have "$t" || { echo "error: '$t' is required for the release fallback." >&2; exit 1; }
  done
  case "$(uname -m)" in
    arm64)        ARCH=arm64 ;;
    x86_64|amd64) ARCH=amd64 ;;
    *) echo "error: unsupported arch '$(uname -m)' (need arm64 or x86_64)." >&2; exit 1 ;;
  esac

  BIN_DIR="${GOG_BIN_DIR:-$HOME/.local/bin}"
  mkdir -p "$BIN_DIR"
  GOG_TMP="$(mktemp -d)"
  if [ -n "${GOG_VERSION:-}" ]; then
    base="https://github.com/$REPO/releases/download/v${GOG_VERSION}"
  else
    base="https://github.com/$REPO/releases/latest/download"
  fi

  echo "Fetching checksums..."
  curl -fsSL "$base/checksums.txt" -o "$GOG_TMP/checksums.txt"
  asset="$(awk -v p="_${OS_NAME}_${ARCH}.tar.gz" '$2 ~ p {print $2}' "$GOG_TMP/checksums.txt" | head -1)"
  [ -n "$asset" ] || { echo "error: no ${OS_NAME}_${ARCH} asset found in the release." >&2; exit 1; }

  echo "Downloading $asset..."
  curl -fsSL "$base/$asset" -o "$GOG_TMP/$asset"

  echo "Verifying SHA-256..."
  expected="$(awk -v a="$asset" '$2==a{print $1}' "$GOG_TMP/checksums.txt")"
  actual="$(shasum -a 256 "$GOG_TMP/$asset" | awk '{print $1}')"
  if [ "$expected" != "$actual" ]; then
    echo "error: checksum mismatch for $asset" >&2
    echo "  expected $expected" >&2
    echo "  actual   $actual" >&2
    exit 1
  fi

  echo "Installing gog to $BIN_DIR/gog..."
  tar -xzf "$GOG_TMP/$asset" -C "$GOG_TMP" gog
  install -m 0755 "$GOG_TMP/gog" "$BIN_DIR/gog"
  echo "gog: $("$BIN_DIR/gog" --version)"
  case ":$PATH:" in
    *":$BIN_DIR:"*) : ;;
    *) echo "NOTE: $BIN_DIR is not on your PATH. Add it, e.g.:"
       echo "      echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> ~/.zshrc && exec \$SHELL" ;;
  esac
}

install_skills() {
  local SRC_DIR DEST_DIR installed=0 skipped=0 name dest src
  SRC_DIR="$REPO_DIR/skills"
  DEST_DIR="${CLAUDE_SKILLS_DIR:-$HOME/.claude/skills}"
  [ -d "$SRC_DIR" ] || { echo "error: $SRC_DIR not found (run from the repo root)" >&2; exit 1; }
  mkdir -p "$DEST_DIR"
  for src in "$SRC_DIR"/gog-*/; do
    name="$(basename "$src")"; dest="$DEST_DIR/$name"; src="${src%/}"
    if [ -L "$dest" ]; then
      ln -sfn "$src" "$dest"; echo "updated  $name"; installed=$((installed + 1))
    elif [ -e "$dest" ]; then
      echo "SKIP     $name (a non-symlink already exists at $dest)" >&2; skipped=$((skipped + 1))
    else
      ln -s "$src" "$dest"; echo "linked   $name"; installed=$((installed + 1))
    fi
  done
  echo "Linked $installed skill(s) into $DEST_DIR${skipped:+, skipped $skipped}."
}

if [ "$SKILLS_ONLY" -ne 1 ]; then
  echo "== gog CLI =="
  install_gog
  echo
fi
if [ "$GOG_ONLY" -ne 1 ]; then
  echo "== skills =="
  install_skills
  echo
fi
echo "Done. Start (or restart) Claude Code to pick up the skills. Verify with:"
echo "  gog --version && gog auth list --check --json --no-input"
