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

PLANE_GITHUB_HOST="github.com"
PLANE_GITHUB_REPOSITORY="planehq/plane"
PLANE_GITHUB_SCOPES="read:packages,admin:ssh_signing_key"
PLANE_WORKSTATION_DIRECTORY="${PLANE_WORKSTATION_DIRECTORY:-$HOME/Developer/plane}"

info() {
  printf '\n==> %s\n' "$*"
}

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

ensure_command_line_tools() {
  local attempt

  if /usr/bin/xcode-select -p >/dev/null 2>&1; then
    return 0
  fi

  info "Starting the Xcode Command Line Tools installer"
  /usr/bin/xcode-select --install >/dev/null 2>&1 || true
  printf '%s\n' "Complete the macOS installation prompt. Setup will continue automatically."

  for attempt in {1..360}; do
    if /usr/bin/xcode-select -p >/dev/null 2>&1; then
      return 0
    fi
    sleep 5
  done

  fail "Xcode Command Line Tools did not become available within 30 minutes. Rerun this setup after installation finishes."
}

load_homebrew() {
  local prefix

  if command -v brew >/dev/null 2>&1; then
    return 0
  fi

  for prefix in /opt/homebrew /usr/local; do
    if [[ -x "$prefix/bin/brew" ]]; then
      eval "$("$prefix/bin/brew" shellenv zsh)"
      return 0
    fi
  done

  return 1
}

ensure_homebrew() {
  if load_homebrew; then
    return 0
  fi

  info "Installing Homebrew"
  # Keep this revision and digest in sync with tasks/setup-mac.
  (
    installer_dir="$(mktemp -d "${TMPDIR:-/tmp}/plane-homebrew.XXXXXX")" || exit 1
    trap 'rm -rf "$installer_dir"' EXIT
    /usr/bin/curl -fsSL \
      https://raw.githubusercontent.com/Homebrew/install/7a133dcc74051ee4efc79467ed215dfedf45aea2/install.sh \
      -o "$installer_dir/install.sh" || exit 1
    printf '%s  %s\n' \
      12479a24be3f5307eecac7cde670fad7118640f031229e964f544b1367b52a41 \
      "$installer_dir/install.sh" | /usr/bin/shasum -a 256 -c - || exit 1
    /bin/bash "$installer_dir/install.sh"
  ) || return $?
  load_homebrew || fail "Homebrew was installed but could not be loaded into this shell."
}

github_auth_has_scope() {
  local required_scope="$1"
  local scopes

  scopes="$(gh auth status --active --hostname "$PLANE_GITHUB_HOST" --json hosts \
    --jq ".hosts[\"$PLANE_GITHUB_HOST\"][] | select(.active) | .scopes" 2>/dev/null)" || return 1

  [[ ",${scopes// /}," == *",${required_scope},"* ]]
}

ensure_github_auth() {
  local token_source

  unset GH_TOKEN GITHUB_TOKEN

  if ! gh auth status --active --hostname "$PLANE_GITHUB_HOST" >/dev/null 2>&1; then
    info "Signing in to GitHub"
    gh auth login \
      --web \
      --git-protocol https \
      --hostname "$PLANE_GITHUB_HOST" \
      --scopes "$PLANE_GITHUB_SCOPES"
  elif ! github_auth_has_scope "read:packages" || ! github_auth_has_scope "admin:ssh_signing_key"; then
    info "Authorizing GitHub package access and signing-key setup"
    gh auth refresh \
      --hostname "$PLANE_GITHUB_HOST" \
      --scopes "$PLANE_GITHUB_SCOPES"
  fi

  gh config set git_protocol https --host "$PLANE_GITHUB_HOST"
  gh auth setup-git --hostname "$PLANE_GITHUB_HOST"

  token_source="$(gh auth status --active --hostname "$PLANE_GITHUB_HOST" --json hosts \
    --jq ".hosts[\"$PLANE_GITHUB_HOST\"][] | select(.active) | .tokenSource")" || return $?

  if [[ "$token_source" != "keyring" ]]; then
    fail "GitHub CLI is not using macOS Keychain (credential source: ${token_source:-unknown})."
  fi
}

clone_plane() {
  local origin

  if [[ -d "$PLANE_WORKSTATION_DIRECTORY/.git" ]]; then
    origin="$(git -C "$PLANE_WORKSTATION_DIRECTORY" remote get-url origin 2>/dev/null || true)"
    case "$origin" in
      https://github.com/planehq/plane|https://github.com/planehq/plane.git|git@github.com:planehq/plane.git|ssh://git@github.com/planehq/plane.git)
        if [[ ! -x "$PLANE_WORKSTATION_DIRECTORY/bin/setup-workstation" ]]; then
          fail "$PLANE_WORKSTATION_DIRECTORY does not contain an executable bin/setup-workstation. Update this checkout to include the current main branch, then rerun setup. Setup has not changed this checkout."
        fi
        git -C "$PLANE_WORKSTATION_DIRECTORY" remote set-url origin https://github.com/planehq/plane.git
        return 0
        ;;
      *)
        fail "$PLANE_WORKSTATION_DIRECTORY already contains a different git repository."
        ;;
    esac
  fi

  if [[ -e "$PLANE_WORKSTATION_DIRECTORY" ]]; then
    fail "$PLANE_WORKSTATION_DIRECTORY already exists but is not a Plane git checkout."
  fi

  mkdir -p "$(dirname "$PLANE_WORKSTATION_DIRECTORY")"
  gh repo clone "$PLANE_GITHUB_REPOSITORY" "$PLANE_WORKSTATION_DIRECTORY"
  git -C "$PLANE_WORKSTATION_DIRECTORY" remote set-url origin https://github.com/planehq/plane.git
}

if [[ "$(uname -s)" != "Darwin" ]]; then
  fail "This bootstrap currently supports macOS only."
fi

info "Preparing this Mac for Plane development"
ensure_command_line_tools
ensure_homebrew

info "Installing GitHub CLI"
brew install gh

ensure_github_auth

info "Cloning Plane"
clone_plane

info "Handing off to Plane's versioned workstation setup"
exec "$PLANE_WORKSTATION_DIRECTORY/bin/setup-workstation"
