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

print_command=false
public_key_material=""
private_key_override=""
remote_command=""
if [[ "${1:-}" == "ssh" ]]; then
    shift
fi
while (($# > 0)); do
    case "$1" in
        --print-command) print_command=true; shift ;;
        --public-key) public_key_material="${2:-}"; shift 2 ;;
        --private-key-path) private_key_override="${2:-}"; shift 2 ;;
        --command) remote_command="${2:-}"; shift 2 ;;
        --) shift; break ;;
        *) break ;;
    esac
done

oci_bin="${OCI_CLI_BIN:-}"
if [[ -z "${oci_bin}" ]]; then
    if command -v oci >/dev/null 2>&1; then
        oci_bin="$(command -v oci)"
    else
        oci_bin="${HOME}/.local/share/homelab/venvs/oci-cli/bin/oci"
    fi
fi

bastion_id="${1:-${LAB_OCI_BASTION_ID:-}}"
target_id="${2:-${LAB_OCI_TARGET_INSTANCE_ID:-${LAB_OCI_EDGE_INSTANCE_ID:-${LAB_OCI_EDGE_EXISTING_INSTANCE_ID:-}}}}"
target_user="${3:-${LAB_OCI_BASTION_TARGET_USER:-ubuntu}}"
public_key="${4:-${LAB_OCI_SSH_PUBLIC_KEY_PATH:-${HOME}/.ssh/id_ed25519.pub}}"
private_key="${5:-${LAB_OCI_SSH_PRIVATE_KEY_PATH:-${public_key%.pub}}}"
if [[ -n "${private_key_override}" ]]; then
    private_key="${private_key_override}"
fi
session_ttl="${LAB_OCI_BASTION_SESSION_TTL:-3600}"

if [[ ! -x "${oci_bin}" ]]; then
    echo "OCI CLI is not installed; run ./jeannie oci-auth install." >&2
    exit 2
fi
if [[ -z "${bastion_id}" || -z "${target_id}" ]]; then
    echo "Usage: ./jeannie oci bastion ssh [--print-command] [--public-key 'OPENSSH_PUBLIC_KEY'] [--private-key-path PATH] [BASTION_OCID] [TARGET_INSTANCE_OCID] [OS_USER] [SSH_PUBLIC_KEY] [SSH_PRIVATE_KEY]" >&2
    echo "Set LAB_OCI_BASTION_ID and LAB_OCI_EDGE_INSTANCE_ID to omit the OCIDs." >&2
    exit 2
fi
temporary_public_key=""
cleanup_public_key() { [[ -n "${temporary_public_key}" ]] && rm -f "${temporary_public_key}"; }
trap cleanup_public_key EXIT
if [[ -n "${public_key_material}" ]]; then
    temporary_public_key="$(mktemp)"
    printf '%s\n' "${public_key_material}" >"${temporary_public_key}"
    public_key="${temporary_public_key}"
fi
[[ -f "${public_key}" ]] || { echo "SSH public key not found: ${public_key}" >&2; exit 2; }
if [[ "${print_command}" != true ]]; then
    [[ -f "${private_key}" ]] || { echo "SSH private key not found: ${private_key}" >&2; exit 2; }
fi

session_json="$("${oci_bin}" bastion session create-managed-ssh \
    --bastion-id "${bastion_id}" \
    --target-resource-id "${target_id}" \
    --target-os-username "${target_user}" \
    --ssh-public-key-file "${public_key}" \
    --session-ttl "${session_ttl}" \
    --wait-for-state SUCCEEDED \
    --output json)"
session_id="$(printf '%s' "${session_json}" | python3 -c 'import json,sys; print(json.load(sys.stdin)["data"]["id"])')"
ssh_command="$("${oci_bin}" bastion session get \
    --session-id "${session_id}" \
    --query 'data."ssh-metadata".command' \
    --raw-output)"
ssh_command="${ssh_command//<privateKey>/${private_key}}"
if [[ -n "${remote_command}" ]]; then
    ssh_command+=" -- ${remote_command}"
fi
if [[ "${print_command}" == true ]]; then
    printf 'session_id=%s\n' "${session_id}"
    printf 'ssh_command=%s\n' "${ssh_command}"
    exit 0
fi
printf 'Connecting through OCI Bastion session %s...\n' "${session_id}" >&2
exec bash -c "${ssh_command}"
