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

CA_URL="${CA_URL:-https://10.10.40.53}"
CA_FINGERPRINT="${CA_FINGERPRINT:-5fc8c379cab1119c1a9ac7038225f6bcf3a2ffb0e71b257af796b2bd6c71d594}"
FORCE="${FORCE:-0}"

log() {
  printf '\n[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"
}

fail() {
  echo "ERROR: $*" >&2
  exit 1
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1
}

is_root() {
  [ "$(id -u)" -eq 0 ]
}

as_root() {
  if is_root; then
    "$@"
  else
    sudo "$@"
  fi
}

detect_os() {
  case "$(uname -s)" in
    Linux*) echo "linux" ;;
    Darwin*) echo "darwin" ;;
    MINGW*|MSYS*|CYGWIN*) echo "windows_bash" ;;
    *) echo "unknown" ;;
  esac
}

install_step() {
  if need_cmd step; then
    log "step CLI already installed"
    return
  fi

  case "$(detect_os)" in
    darwin)
      need_cmd brew || fail "Homebrew not found"
      log "Installing step with Homebrew"
      brew install step
      ;;

    linux)
      if need_cmd apt-get; then
        log "Installing step-cli with apt"
        as_root apt-get update
        as_root apt-get install -y --no-install-recommends curl gpg ca-certificates
        as_root mkdir -p /etc/apt/keyrings
        curl -fsSL https://packages.smallstep.com/keys/apt/repo-signing-key.gpg | \
          as_root tee /etc/apt/keyrings/smallstep.asc >/dev/null

        tmpfile="$(mktemp)"
        cat > "$tmpfile" <<'EOF'
Types: deb
URIs: https://packages.smallstep.com/stable/debian
Suites: debs
Components: main
Signed-By: /etc/apt/keyrings/smallstep.asc
EOF
        as_root cp "$tmpfile" /etc/apt/sources.list.d/smallstep.sources
        rm -f "$tmpfile"

        as_root apt-get update
        as_root apt-get install -y step-cli

      elif need_cmd apk; then
        log "Installing step-cli with apk"
        as_root apk add --no-cache step-cli

      elif need_cmd dnf; then
        log "Installing step-cli with dnf"
        tmpfile="$(mktemp)"
        cat > "$tmpfile" <<'EOF'
[smallstep]
name=Smallstep
baseurl=https://packages.smallstep.com/stable/fedora/
enabled=1
repo_gpgcheck=0
gpgcheck=1
gpgkey=https://packages.smallstep.com/keys/smallstep-0x889B19391F774443.gpg
EOF
        as_root cp "$tmpfile" /etc/yum.repos.d/smallstep.repo
        rm -f "$tmpfile"

        as_root dnf makecache
        as_root dnf install -y step-cli

      elif need_cmd pacman; then
        log "Installing step-cli with pacman"
        as_root pacman -Sy --noconfirm step-cli
        if [ ! -e /usr/local/bin/step ] && [ -x /usr/bin/step-cli ]; then
          as_root ln -s /usr/bin/step-cli /usr/local/bin/step
        fi

      else
        fail "No supported package manager found"
      fi
      ;;

    *)
      fail "Unsupported OS"
      ;;
  esac

  need_cmd step || fail "step CLI installation failed"
}

bootstrap_step() {
  if [ "$FORCE" = "1" ]; then
    rm -rf "$HOME/.step"
  fi

  log "Bootstrapping against $CA_URL"
  step ca bootstrap \
    --ca-url "$CA_URL" \
    --fingerprint "$CA_FINGERPRINT" \
    --install \
    --force
}

install_linux_trust() {
  local root_cert="$HOME/.step/certs/root_ca.crt"
  [ -f "$root_cert" ] || fail "Root certificate not found at $root_cert"

  if need_cmd update-ca-certificates; then
    as_root mkdir -p /usr/local/share/ca-certificates
    as_root cp "$root_cert" /usr/local/share/ca-certificates/insmw-root-ca.crt
    as_root update-ca-certificates
    return
  fi

  if need_cmd trust; then
    as_root trust anchor "$root_cert"
    return
  fi

  fail "Could not determine Linux trust-store tool"
}

install_macos_trust() {
  local root_cert="$HOME/.step/certs/root_ca.crt"
  [ -f "$root_cert" ] || fail "Root certificate not found at $root_cert"

  as_root security add-trusted-cert \
    -d \
    -r trustRoot \
    -k /Library/Keychains/System.keychain \
    "$root_cert"
}

install_trust_store() {
  case "$(detect_os)" in
    linux) install_linux_trust ;;
    darwin) install_macos_trust ;;
    *) fail "Unsupported OS for trust-store installation" ;;
  esac
}

main() {
  install_step
  bootstrap_step
  install_trust_store
  log "Done"
}

main "$@"