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

action="${1:-check}"
if [[ "${JEANNIE_REMOTE_SERVER:-false}" == "true" && "${action}" == "init" ]]; then
  echo "oci-auth init requires an interactive Debian session; run it directly on the Debian host." >&2
  exit 2
fi

profile="${OCI_CLI_PROFILE:-${OCI_CONFIG_PROFILE:-DEFAULT}}"
config_file="${OCI_CONFIG_FILE:-${HOME}/.oci/config}"
key_file="${OCI_PRIVATE_KEY_PATH:-${HOME}/.oci/oci_api_key.pem}"
public_key_file="${key_file}.pub"
cli_venv="${OCI_CLI_VENV:-${HOME}/.local/share/homelab/venvs/oci-cli}"
oci_bin=""

resolve_oci_bin() {
  if command -v oci >/dev/null 2>&1; then
    oci_bin="$(command -v oci)"
  elif [[ -x "${cli_venv}/bin/oci" ]]; then
    oci_bin="${cli_venv}/bin/oci"
  fi
}

install_cli() {
  command -v python3 >/dev/null 2>&1 || { echo "python3 is required to install OCI CLI." >&2; return 1; }
  mkdir -p "$(dirname "${cli_venv}")"
  if [[ ! -x "${cli_venv}/bin/python" ]]; then
    python3 -m venv "${cli_venv}"
  fi
  "${cli_venv}/bin/python" -m pip install --upgrade pip oci-cli
  echo "OCI CLI installed at ${cli_venv}/bin/oci"
}

fingerprint_for_key() {
  openssl rsa -in "$1" -pubout -outform DER 2>/dev/null \
    | openssl md5 -c 2>/dev/null \
    | awk '{print $2}'
}

check_auth() {
  local fingerprint
  [[ -r "${config_file}" ]] || { echo "OCI config missing: ${config_file}" >&2; return 1; }
  [[ -r "${key_file}" ]] || { echo "OCI private key missing: ${key_file}" >&2; return 1; }
  fingerprint="$(fingerprint_for_key "${key_file}")"
  [[ -n "${fingerprint}" ]] || { echo "Unable to calculate key fingerprint." >&2; return 1; }
  echo "OCI config: ${config_file}"
  echo "OCI profile: ${profile}"
  echo "Key fingerprint: ${fingerprint}"
  resolve_oci_bin
  if [[ -n "${oci_bin}" ]]; then
    "${oci_bin}" iam region list --config-file "${config_file}" --profile "${profile}" \
      --query 'data[0].name' --raw-output >/dev/null
    echo "OCI API authentication: OK"
  else
    echo "OCI CLI not installed; local config/key validation passed. Run ./jeannie oci-auth install."
  fi
}

init_auth() {
  local tenancy user region fingerprint force="false"
  if [[ "${2:-}" == "--force" ]]; then
    force="true"
  elif [[ -e "${config_file}" && "${profile}" == "DEFAULT" ]]; then
    echo "Refusing to overwrite ${config_file}; use --force only if you intend to replace the profile." >&2
    return 2
  fi

  mkdir -p "$(dirname "${config_file}")"
  chmod 700 "$(dirname "${config_file}")"
  if [[ ! -e "${key_file}" ]]; then
    echo "Generating RSA API signing key at ${key_file}..."
    openssl genrsa -out "${key_file}" 2048 >/dev/null 2>&1
    chmod 600 "${key_file}"
  elif [[ "${force}" == "true" ]]; then
    chmod 600 "${key_file}"
  fi
  openssl rsa -in "${key_file}" -pubout -out "${public_key_file}" 2>/dev/null
  chmod 644 "${public_key_file}"

  read -r -p "OCI tenancy OCID: " tenancy
  read -r -p "OCI user OCID: " user
  read -r -p "OCI region [${OCI_REGION:-us-phoenix-1}]: " region
  region="${region:-${OCI_REGION:-us-phoenix-1}}"
  fingerprint="$(fingerprint_for_key "${key_file}")"

  CONFIG_FILE="${config_file}" PROFILE="${profile}" TENANCY="${tenancy}" USER_OCID="${user}" \
    REGION="${region}" FINGERPRINT="${fingerprint}" KEY_FILE="${key_file}" \
    python3 - <<'PY'
import configparser, os
path = os.environ["CONFIG_FILE"]
profile = os.environ["PROFILE"]
parser = configparser.ConfigParser(interpolation=None)
parser.optionxform = str
if os.path.exists(path):
    parser.read(path)
parser[profile] = {
    "user": os.environ["USER_OCID"],
    "fingerprint": os.environ["FINGERPRINT"],
    "tenancy": os.environ["TENANCY"],
    "region": os.environ["REGION"],
    "key_file": os.environ["KEY_FILE"],
}
with open(path, "w", encoding="utf-8") as handle:
    parser.write(handle)
os.chmod(path, 0o600)
PY

  echo "Wrote ${config_file} profile ${profile}."
  echo "Upload this public key to the OCI user before running the check:"
  cat "${public_key_file}"
  echo "Fingerprint: ${fingerprint}"
  echo "Run: ./jeannie oci-auth check"
}

case "${action}" in
  install) install_cli ;;
  init) init_auth "$@" ;;
  check) check_auth ;;
  *) echo "Usage: ./jeannie oci-auth {install|init [--force]|check}" >&2; exit 2 ;;
esac
