#!/bin/bash
# Get the orion repo onto a new Mac, then hand off to `orion setup`.
#
#   curl -fsS https://orion-setup.drata.com | bash
#
# tools/setup/worker serves this file (behind Cloudflare Access).
#
# This script does ONLY what is needed to clone orion:
#   1. git (Apple's Command Line Tools)
#   2. a GitHub sign-in, with a temporary copy of the GitHub CLI that is deleted at the end
#   3. the orion clone
# It never installs Homebrew or any other tool. `orion setup` installs and checks those on
# every run, from toolchain.yml. Add a tool there, never here. Safe to run again.
# Parse the whole body before running it: a cut-off download must do nothing.
main() {
  set -euo pipefail

  ORG=drata
  ROOT="${ORION_ROOT:-$HOME/Projects/drata}"
  say() { printf '\n==> %s\n' "$*"; }

  # 1. git
  if ! xcode-select -p >/dev/null 2>&1; then
    say "Installing Apple's Command Line Tools (they include git)."
    echo "A window opens. Choose Install, and wait for it to finish. This can take 10 minutes."
    xcode-select --install >/dev/null 2>&1 || true
    until xcode-select -p >/dev/null 2>&1; do sleep 5; done
  fi

  if [ ! -d "$ROOT/orion/.git" ]; then
    # 2. A GitHub sign-in. Use the GitHub CLI if it is here; else a temporary, checked copy.
    tmp="$(mktemp -d)"
    trap 'rm -rf "$tmp"' EXIT
    gh="$(command -v gh || true)"
    if [ -z "$gh" ]; then
      arch="$(uname -m)"
      [ "$arch" = x86_64 ] && arch=amd64
      latest="$(curl -fsSI -o /dev/null -w '%{redirect_url}' https://github.com/cli/cli/releases/latest)"
      v="${latest##*/v}"
      base="https://github.com/cli/cli/releases/download/v$v"
      zip="gh_${v}_macOS_${arch}.zip"
      curl -fsSL -o "$tmp/$zip" "$base/$zip"
      curl -fsSL -o "$tmp/sums.txt" "$base/gh_${v}_checksums.txt"
      (cd "$tmp" && grep " $zip\$" sums.txt | shasum -a 256 -c - >/dev/null) || {
        echo "The GitHub CLI download did not match its checksum. Run this again."
        exit 1
      }
      unzip -q "$tmp/$zip" -d "$tmp"
      gh="$tmp/gh_${v}_macOS_${arch}/bin/gh"
    fi

    if ! "$gh" auth status --hostname github.com >/dev/null 2>&1; then
      say "Sign in to GitHub."
      echo "It copies a one-time code for you. Press Enter, and your browser opens."
      echo "Paste the code (Command and V), choose Continue, then Authorize."
      echo "If you see drata with an Authorize button, choose that too."
      echo "If Terminal asks a yes-or-no question, press Enter."
      "$gh" auth login --hostname github.com --web --clipboard --git-protocol https
    fi

    # 3. The orion clone
    say "Downloading the orion repo to $ROOT/orion"
    mkdir -p "$ROOT"
    if ! "$gh" repo clone "$ORG/orion" "$ROOT/orion"; then
      me="$("$gh" api user --jq .login 2>/dev/null || echo "your GitHub username")"
      case "$("$gh" api "user/memberships/orgs/$ORG" --jq .state 2>&1)" in
        pending) echo "Accept your $ORG invite at https://github.com/orgs/$ORG/invitation" ;;
        active | *SAML* | *SSO*) echo "Open https://github.com/orgs/$ORG/sso and sign in with your Drata account." ;;
        *) echo "Your GitHub account ($me) is not in $ORG. Send IT that username and ask them to add it." ;;
      esac
      echo "Then run this again: curl -fsS https://orion-setup.drata.com | bash"
      exit 1
    fi

    # The sign-in stays in the Keychain. `orion setup` points git at the permanent GitHub CLI.
    rm -rf "$tmp"
    trap - EXIT
  else
    # Already here: start the newest setup. A clone that is not on a clean main stays as it is.
    git -C "$ROOT/orion" pull --ff-only --quiet 2>/dev/null || true
  fi

  say "orion is ready. Starting the setup."
  exec "$ROOT/orion/setup"
}

# Piped from curl, stdin is the script: read prompts from the keyboard instead.
if [ ! -t 0 ] && (: </dev/tty) 2>/dev/null; then main </dev/tty; else main; fi
