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

# Logging
BOLD='\033[1m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
DIM='\033[2m'
NC='\033[0m'

info()    { echo -e "${BOLD}${GREEN}✔${NC} $*"; }
step()    { echo -e "\n${BOLD}▶ $*${NC}"; }
skip()    { echo -e "${DIM}  ↩ $* (skipping)${NC}"; }
error()   { echo -e "${RED}✖ $*${NC}" >&2; }

# Check dependencies
step "Checking dependencies..."

MISSING_DEPS=()

command -v brew &>/dev/null || MISSING_DEPS+=("brew (https://brew.sh)")
command -v aws  &>/dev/null || MISSING_DEPS+=("awscli (brew install awscli)")

if [[ ${#MISSING_DEPS[@]} -gt 0 ]]; then
  error "Missing dependencies:"
  printf '  - %s\n' "${MISSING_DEPS[@]}"
  exit 1
fi

# Install granted
step "Installing Granted..."

if command -v granted &>/dev/null; then
  skip "granted already installed"
else
  brew tap common-fate/granted
  brew install common-fate/granted/granted
fi

# Configure granted registry
step "Configuring Granted..."

REGISTRY_URL="git@github.com:Lawhive/lawhive.infra.cloud.git"

if granted registry list 2> >(grep -q "this") ; then
  skip "granted registry 'this' already configured"
else
  echo ""
  echo "Select your group:"
  select GROUP in admins data dev infra noop poweruser researcher; do
    [[ -n "$GROUP" ]] && break
    echo "Invalid selection, please try again."
  done

  granted registry add --name this --url "$REGISTRY_URL" --path "iam/granted-registry/groups/$GROUP"
  info "Registry configured"
fi

granted settings set --setting=CredentialProcessAutoLogin --value true

# Install lhctl
step "Installing lhctl..."

RELEASES_BUCKET="shr-lhctl-releases-dist"
RELEASES_REGION="eu-west-2"
RELEASES_PROFILE="shr"
ASSET_NAME="lhctl.darwin-arm64"
INSTALL_DIR="$HOME/.local/bin"
TMP_PATH="/tmp/lhctl"

if command -v lhctl &>/dev/null; then
  skip "lhctl already installed"
else
  mkdir -p "$INSTALL_DIR"

  LATEST_VERSION=$(aws s3 cp "s3://$RELEASES_BUCKET/releases/latest" - \
    --region "$RELEASES_REGION" --profile "$RELEASES_PROFILE")

  aws s3 cp "s3://$RELEASES_BUCKET/releases/$LATEST_VERSION/$ASSET_NAME" $TMP_PATH \
    --region "$RELEASES_REGION" --profile "$RELEASES_PROFILE"

  info "Downloaded lhctl $LATEST_VERSION"
  echo -e "  ${DIM}Verifying checksum...${NC}"

  EXPECTED_SHA=$(aws s3 cp "s3://$RELEASES_BUCKET/releases/$LATEST_VERSION/${ASSET_NAME}.sha256" - \
    --region "$RELEASES_REGION" --profile "$RELEASES_PROFILE" | awk '{print $1}')
  ACTUAL_SHA=$(shasum -a 256 $TMP_PATH | awk '{print $1}')

  if [[ "$EXPECTED_SHA" != "$ACTUAL_SHA" ]]; then
    error "Checksum mismatch for lhctl binary, aborting"
    rm $TMP_PATH
    exit 1
  fi

  install -m 755 $TMP_PATH "$INSTALL_DIR/lhctl"
  info "lhctl $LATEST_VERSION installed to $INSTALL_DIR/lhctl"
fi

echo -e "\n${BOLD}${GREEN}Setup complete${NC}"
