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

if [[ "${1:-}" == "ssh" ]]; then
    shift
fi

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}}}"
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 [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
[[ -f "${public_key}" ]] || { echo "SSH public key not found: ${public_key}" >&2; exit 2; }
[[ -f "${private_key}" ]] || { echo "SSH private key not found: ${private_key}" >&2; exit 2; }

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}}"
printf 'Connecting through OCI Bastion session %s...\n' "${session_id}" >&2
exec bash -c "${ssh_command}"
