#!/bin/bash

set -euo pipefail

REPO="glssolutions/anduril"
ANDURIL_DIR="$HOME/.local/share/anduril"
ANDURIL_MIGRATIONS_STATE_DIR="$HOME/.local/state/anduril/migrations"
ANDURIL_MIGRATIONS_SKIPPED_DIR="$ANDURIL_MIGRATIONS_STATE_DIR/skipped"

ansi_art=$(cat <<'EOF'
                          █████                       ███  ████ 
                         ░░███                       ░░░  ░░███ 
  ██████   ████████    ███████  █████ ████ ████████  ████  ░███ 
 ░░░░░███ ░░███░░███  ███░░███ ░░███ ░███ ░░███░░███░░███  ░███ 
  ███████  ░███ ░███ ░███ ░███  ░███ ░███  ░███ ░░░  ░███  ░███ 
 ███░░███  ░███ ░███ ░███ ░███  ░███ ░███  ░███      ░███  ░███ 
░░████████ ████ █████░░████████ ░░████████ █████     █████ █████
 ░░░░░░░░ ░░░░ ░░░░░  ░░░░░░░░   ░░░░░░░░ ░░░░░     ░░░░░ ░░░░░ 
                                                                
                                                                
EOF
)

clear
echo -e "\n$ansi_art\n"

if ! gh auth status -h github.com >/dev/null 2>&1; then
  if [[ -t 0 && -t 1 ]]; then
    gum style --border normal --padding "1 2" \
      "GitHub CLI is not authenticated for github.com." \
      "" \
      "Anduril needs GitHub access to clone $REPO."

    if gum confirm "Run 'gh auth login -h github.com --git-protocol ssh' now?"; then
      gh auth login -h github.com --git-protocol ssh
    else
      echo "Aborting. Authenticate first with: gh auth login -h github.com --git-protocol ssh"
      exit 1
    fi
  else
    echo "GitHub CLI is not authenticated for github.com."
    echo "Run: gh auth login -h github.com --git-protocol ssh"
    exit 1
  fi
fi

gh config set git_protocol ssh --host github.com >/dev/null

GH_USER="$(gh api user -q .login 2>/dev/null || true)"
if [[ -n "$GH_USER" ]]; then
  echo "GitHub CLI authenticated as: $GH_USER"
fi

mkdir -p "$(dirname "$ANDURIL_DIR")"
mkdir -p "$ANDURIL_MIGRATIONS_STATE_DIR" "$ANDURIL_MIGRATIONS_SKIPPED_DIR"

if [[ -d "$ANDURIL_DIR/.git" ]]; then
  echo "Updating existing Anduril checkout at $ANDURIL_DIR..."
  git -C "$ANDURIL_DIR" pull --ff-only
else
  echo "Cloning $REPO into $ANDURIL_DIR..."
  gh repo clone "$REPO" "$ANDURIL_DIR"
fi

"$ANDURIL_DIR/bin/anduril-install"
