#!/bin/bash
set -eu

MAP="/data/layerops/ssh/mapping.json"

# Args from authorized_keys, e.g. --allow nginx,haproxy
ALLOW=""
if [ "${1:-}" = "--allow" ]; then
  ALLOW="${2:-}"
  shift 2
fi

UUID="${SSH_ORIGINAL_COMMAND:-}"
[ -n "$UUID" ] || { echo "usage: ssh … <uuid>" >&2; exit 2; }
case "$UUID" in *[!A-Za-z0-9-]*|"") echo "invalid uuid" >&2; exit 1;; esac

[ -r "$MAP" ] || { echo "mapping unavailable"; exit 1; }

# Mapping is now JSON objects: sshUuid, privateIp, containerId, command, serviceType
ENTRY=$(jq -r --arg u "$UUID" '
  (if type=="array" then .[] else . end)
  | select(.sshUuid==$u)
  | [.privateIp, .containerId, .command, (.serviceType // "")]
  | @tsv
' "$MAP" 2>/dev/null || true)
[ -n "$ENTRY" ] || { echo "unknown uuid"; exit 1; }

IFS=$'\t' read -r _VM_IP CONT CMD SVC_TYPE <<EOF
$ENTRY
EOF
[ -n "$_VM_IP" ] || { echo "bad map format: missing privateIp"; exit 1; }
[ -n "$CONT" ] || { echo "bad map format: missing containerId"; exit 1; }

# ACL: ensure CONT is allowed for this key
if [ -n "$ALLOW" ]; then
  # split commas/spaces; require exact match
  ok=0
  for a in $(printf "%s" "$ALLOW" | tr ',' ' '); do
    [ "$a" = "$CONT" ] && ok=1 && break
  done
  [ "$ok" -eq 1 ] || { echo "forbidden" >&2; exit 1; }
fi

# Allocate TTY if available
if [ -t 0 ]; then IT="-it"; else IT="-i"; fi

# Run the exact mapped command inside the container
if [ "$SVC_TYPE" = "system_container" ]; then
  # System containers use Incus
  exec /usr/bin/incus exec "$CONT" -- $CMD
else
  # Docker containers (default)
  exec /usr/bin/docker exec $IT \
    -e TERM="${TERM:-xterm-256color}" \
    -e COLUMNS="${COLUMNS:-80}" \
    -e LINES="${LINES:-24}" \
    "$CONT" $CMD
fi