#!/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, from Apple's Command Line Tools. Install them from the command line, the way
  # Homebrew does: no window, and no 24 GB free-space check (the window wants that much,
  # though the tools download about 1 GB).
  if ! xcode-select -p >/dev/null 2>&1; then
    say "Installing Apple's Command Line Tools (they include git). This takes a few minutes."
    echo "When it asks for your password, type your Mac password and press Enter."
    echo "Nothing shows as you type. That is normal."
    marker=/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
    trap 'rm -f "$marker"' EXIT
    touch "$marker" || true
    # A failed scan must reach Apple's window below, not end the script.
    label="$(softwareupdate --list 2>/dev/null | sed -n 's/^ *\* Label: \(Command Line Tools.*\)$/\1/p' | sort -V | tail -n 1 || true)"
    if [ -n "$label" ]; then
      sudo softwareupdate --install "$label" --agree-to-license || true
    fi
    rm -f "$marker" 2>/dev/null || true
    trap - EXIT
    if ! xcode-select -p >/dev/null 2>&1; then  # Software Update did not offer them: use Apple's window
      echo "A window opens. Choose Install, and wait for it to finish."
      xcode-select --install >/dev/null 2>&1 || true
      until xcode-select -p >/dev/null 2>&1; do sleep 5; done
    fi
  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

    sign_in() {
      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 "Then find drata in the list, choose its Authorize button, and sign in with Okta."
      echo "If Terminal asks a yes-or-no question, press Enter."
      "$gh" auth login --hostname github.com --web --clipboard --git-protocol https
    }
    if ! "$gh" auth status --hostname github.com >/dev/null 2>&1; then
      sign_in
    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
        active | *SAML* | *SSO*)
          # Signed in, but drata's single sign-on never approved this sign-in. Only a new
          # sign-in, with drata's Authorize button, approves it.
          say "GitHub needs drata to approve your sign-in. Signing in again."
          "$gh" auth logout --hostname github.com >/dev/null 2>&1 || true
          sign_in
          if ! "$gh" repo clone "$ORG/orion" "$ROOT/orion"; then
            echo "drata still did not approve it. Run this again, and choose Authorize next to drata."
            exit 1
          fi
          ;;
        pending)
          echo "Accept your $ORG invite at https://github.com/orgs/$ORG/invitation"
          echo "Then run this again: curl -fsS https://orion-setup.drata.com | bash"
          exit 1
          ;;
        *)
          echo "Your GitHub account ($me) is not in $ORG. Send IT that username and ask them to add it."
          echo "Then run this again: curl -fsS https://orion-setup.drata.com | bash"
          exit 1
          ;;
      esac
    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"
}

# The terminal's own device (like /dev/ttys003), not /dev/tty: macOS kqueue rejects
# /dev/tty, and tools that use it (Claude Code) crash with "EINVAL: invalid argument, kqueue".
terminal_device() {
  local dev
  dev="/dev/$(ps -o tty= -p $$ | tr -d ' ')"
  if [ -r "$dev" ] && [ -w "$dev" ]; then echo "$dev"; else echo /dev/tty; fi
}

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