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

# Install the zhousc66 Lab Root CA on a managed macOS or Linux client.
#
# Public-portal default:
#   Downloads the Root CA from https://pki.zhoushicheng.cn/certs/.
#
# Safety:
#   - Installs only the public Root CA certificate.
#   - Verifies the SHA256 fingerprint before touching the system trust store.
#   - Never downloads private keys, PFX files, or passphrases.

CA_LABEL="zhousc66 Lab Root CA 2026"
DEFAULT_SOURCE="https://pki.zhoushicheng.cn/certs/zhousc66-lab-root-ca-2026.pem"
EXPECTED_FINGERPRINT="CE:D7:27:9B:6F:B8:F3:92:73:48:48:DD:B5:65:CE:DE:15:28:6E:72:A2:33:E5:51:18:98:D3:A8:95:C2:8F:14"

usage() {
  cat <<EOF
Install the zhousc66 Lab Root CA into this machine's trust store.

Usage:
  $0 [source]

Source defaults to:
  ${DEFAULT_SOURCE}

You can also set ZHOUSC66_CA_SOURCE or pass a local PEM path, HTTPS URL, or scp source:
  ZHOUSC66_CA_SOURCE=/path/to/root.ca.cert.pem $0
  $0 /path/to/root.ca.cert.pem
  $0 https://pki.zhoushicheng.cn/certs/zhousc66-lab-root-ca-2026.pem

The script never stores passwords. If source is an scp remote, scp prompts for auth.
EOF
}

need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "error: required command not found: $1" >&2
    exit 1
  fi
}

fetch_source() {
  local source="$1"
  local target="$2"

  if [[ -f "${source}" ]]; then
    cp "${source}" "${target}"
  elif [[ "${source}" == http://* || "${source}" == https://* ]]; then
    need_cmd curl
    curl -fsSLo "${target}" "${source}"
  else
    need_cmd scp
    scp "${source}" "${target}"
  fi
}

cert_fingerprint() {
  local cert="$1"
  openssl x509 -in "${cert}" -noout -fingerprint -sha256 | sed 's/^.*=//'
}

install_macos() {
  local cert="$1"

  need_cmd security
  sudo security add-trusted-cert \
    -d \
    -r trustRoot \
    -k /Library/Keychains/System.keychain \
    "${cert}"

  security find-certificate \
    -c "${CA_LABEL}" \
    /Library/Keychains/System.keychain >/dev/null
}

install_linux() {
  local cert="$1"

  if command -v update-ca-certificates >/dev/null 2>&1; then
    sudo install -m 0644 "${cert}" \
      /usr/local/share/ca-certificates/zhousc66-lab-root-ca-2026.crt
    sudo update-ca-certificates
    return
  fi

  if command -v update-ca-trust >/dev/null 2>&1; then
    sudo install -m 0644 "${cert}" \
      /etc/pki/ca-trust/source/anchors/zhousc66-lab-root-ca-2026.crt
    sudo update-ca-trust extract
    return
  fi

  echo "error: unsupported Linux trust store; install ${cert} manually" >&2
  exit 1
}

main() {
  if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
    usage
    exit 0
  fi

  need_cmd openssl

  local source="${1:-${ZHOUSC66_CA_SOURCE:-${DEFAULT_SOURCE}}}"
  local workdir="${TMPDIR:-/tmp}/zhousc66-ca-install.$$"
  local cert="${workdir}/root.ca.cert.pem"

  mkdir -p "${workdir}"
  trap 'rm -rf "${workdir}"' EXIT

  echo "Fetching Root CA certificate from: ${source}"
  fetch_source "${source}" "${cert}"

  echo "Validating certificate fingerprint..."
  local actual_fingerprint
  actual_fingerprint="$(cert_fingerprint "${cert}")"
  if [[ "${actual_fingerprint}" != "${EXPECTED_FINGERPRINT}" ]]; then
    echo "error: Root CA fingerprint mismatch" >&2
    echo "expected: ${EXPECTED_FINGERPRINT}" >&2
    echo "actual:   ${actual_fingerprint}" >&2
    exit 1
  fi

  case "$(uname -s)" in
    Darwin)
      install_macos "${cert}"
      ;;
    Linux)
      install_linux "${cert}"
      ;;
    *)
      echo "error: unsupported OS: $(uname -s)" >&2
      exit 1
      ;;
  esac

  echo "Installed and trusted: ${CA_LABEL}"
}

main "$@"
