#!/bin/sh
# LAN-only, Docker-contained relay on the VirtualBox host. No Windows changes.
set -eu
helper_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
repo_root=$(CDPATH= cd -- "$helper_dir/../.." && pwd)
: "${RVBOX_TEST_VBOX_HOST:=helium-remote}"
: "${RVBOX_TEST_VBOX_VM:=rvbox-win10-test}"
: "${RVBOX_TEST_VBOX_VM_UUID:=6cdc114f-71e5-4167-a394-e922e14e6f5c}"
: "${RDP_ACCESS_PROFILE:=default}"
: "${RDP_ACCESS_LAN_BIND:=auto}"
: "${RDP_ACCESS_LAN_CIDR:=auto}"
: "${RDP_ACCESS_LAN_PORT:=3389}"
: "${RDP_ACCESS_VRDE_PORT:=3389}"
: "${RDP_ACCESS_LAN_REMOTE_ROOT:=/home/cabbage/.local/state/rvbox-rdp-access/lan}"

usage() {
    printf '%s\n' 'usage: test/rdp-access/rdp-access lan-up|lan-status|lan-down|lan-clean [--profile NAME] [--lan-bind PRIVATE-IP] [--lan-port PORT] [--lan-cidr SUBNET] [--images]'
    printf '%s\n' 'Defaults: auto-detect the Helium LAN address/subnet, port 3389, profile default.'
    printf '%s\n' 'Only lan-up uses bind/port/cidr overrides. Status/down/clean use saved remote state.'
}
fail() { printf 'lan-access: %s\n' "$*" >&2; exit 2; }
safe_word() { case $2 in ''|-*|*[!A-Za-z0-9._:/@=-]*) fail "$1 contains unsupported characters" ;; esac; }
private_ipv4() {
    printf '%s\n' "$1" | awk -F. '
      NF != 4 { exit 1 }
      { for (i=1;i<=4;i++) if ($i !~ /^[0-9]+$/ || $i+0>255 || (length($i)>1 && substr($i,1,1)=="0")) exit 1 }
      { exit !(($1==10) || ($1==172 && $2>=16 && $2<=31) || ($1==192 && $2==168)) }'
}
port() {
    case $2 in ''|*[!0-9]*) fail "$1 must be numeric" ;; esac
    [ "$2" -ge 1024 ] && [ "$2" -le 65535 ] || fail "$1 must be 1024..65535"
}

action=${1-}
[ -n "$action" ] || { usage; exit 2; }
shift
case $action in --help|-h) usage; exit 0 ;; up|status|down|clean) ;; *) fail 'unknown action' ;; esac
remove_images=false
while [ "$#" -gt 0 ]; do
    case $1 in
        --profile) [ "$#" -ge 2 ] || fail '--profile needs a value'; RDP_ACCESS_PROFILE=$2; shift 2 ;;
        --lan-bind) [ "$#" -ge 2 ] || fail '--lan-bind needs a value'; RDP_ACCESS_LAN_BIND=$2; shift 2 ;;
        --lan-port) [ "$#" -ge 2 ] || fail '--lan-port needs a value'; RDP_ACCESS_LAN_PORT=$2; shift 2 ;;
        --lan-cidr) [ "$#" -ge 2 ] || fail '--lan-cidr needs a value'; RDP_ACCESS_LAN_CIDR=$2; shift 2 ;;
        --images) remove_images=true; shift ;;
        --help|-h) usage; exit 0 ;;
        *) fail "unknown option $1" ;;
    esac
done
case $RDP_ACCESS_PROFILE in ''|*[!a-z0-9-]*|-*) fail 'profile must start with a lowercase alphanumeric and contain only lowercase alphanumeric/hyphen' ;; esac
for name in RVBOX_TEST_VBOX_HOST RVBOX_TEST_VBOX_VM RVBOX_TEST_VBOX_VM_UUID RDP_ACCESS_LAN_REMOTE_ROOT; do
    eval "value=\${$name}"
    safe_word "$name" "$value"
done
case $RDP_ACCESS_LAN_REMOTE_ROOT in
    /home/*/.local/state/*|/srv/*) ;;
    *) fail 'remote root must be a dedicated absolute directory under home/.local/state or /srv' ;;
esac
case $RDP_ACCESS_LAN_REMOTE_ROOT in */../*|*/./*|*/..|*/.|*/) fail 'remote root must be a normalized dedicated directory' ;; esac
port RDP_ACCESS_LAN_PORT "$RDP_ACCESS_LAN_PORT"
port RDP_ACCESS_VRDE_PORT "$RDP_ACCESS_VRDE_PORT"
if [ "$RDP_ACCESS_LAN_BIND" != auto ]; then
    private_ipv4 "$RDP_ACCESS_LAN_BIND" || fail 'LAN bind must be an RFC1918 IPv4 address, never wildcard/loopback/public'
fi
if [ "$RDP_ACCESS_LAN_CIDR" != auto ]; then
    subnet=${RDP_ACCESS_LAN_CIDR%/*}; bits=${RDP_ACCESS_LAN_CIDR##*/}
    private_ipv4 "$subnet" || fail 'LAN subnet must use a private IPv4 address'
    case $bits in ''|*[!0-9]*) fail 'LAN subnet needs a numeric prefix length' ;; esac
    [ "$bits" -ge 8 ] && [ "$bits" -le 32 ] || fail 'LAN subnet prefix must be 8..32'
    # Do not permit a mask broader than the private address block itself.
    case $subnet in 172.*) [ "$bits" -ge 12 ] || fail '172 LAN subnet prefix must be at least /12' ;; 192.*) [ "$bits" -ge 16 ] || fail '192 LAN subnet prefix must be at least /16' ;; esac
fi
[ "$remove_images" = false ] || [ "$action" = clean ] || fail '--images is valid only with lan-clean'
if [ "$action" = up ]; then
    fixture_status=$("$repo_root/scripts/windows/test-host" status) || fail 'fixture identity check failed'
    case $fixture_status in *'state=running') ;; *) fail 'prepare/start the VM first; lan-up never resets or boots it' ;; esac
fi
compose_encoded=$(base64 -w 0 "$helper_dir/compose-lan.yaml")
profile=$RDP_ACCESS_PROFILE
remote_dir=$RDP_ACCESS_LAN_REMOTE_ROOT/$profile
project=rvbox-rdp-lan-$profile

# One SSH round trip for host-side detection, deployment, readiness and state.
# Values crossing the shell boundary have been constrained above; no credentials
# are copied or passed to the relay. Existing VBoxAuthSimple stays authoritative.
run_remote() {
ssh -o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=10 -o ServerAliveCountMax=2 "$RVBOX_TEST_VBOX_HOST" \
    "sh -s -- '$action' '$remote_dir' '$project' '$profile' '$RVBOX_TEST_VBOX_VM' '$RVBOX_TEST_VBOX_VM_UUID' '$RDP_ACCESS_LAN_BIND' '$RDP_ACCESS_LAN_PORT' '$RDP_ACCESS_LAN_CIDR' '$RDP_ACCESS_VRDE_PORT' '$compose_encoded' '$remove_images'" <<'REMOTE'
set -eu
action=$1; dir=$2; project=$3; profile=$4; vm=$5; vm_uuid=$6
bind=$7; lan_port=$8; cidr=$9; shift 9
vrde_port=$1; compose_encoded=$2; remove_images=$3
image=alpine/socat@sha256:82ad20f6f6e29b91ff33b6662d24063522b1378f08fd8569cd3ab412cac13f50
fail() { printf 'remote lan-access: %s\n' "$*" >&2; exit 2; }
compose() { docker compose --project-name "$project" --env-file "$dir/.env" -f "$dir/compose.yaml" "$@"; }
listener() { ss -H -ltn4 | awk -v endpoint="$1:$2" '$4==endpoint { found=1 } END { exit !found }'; }
assert_owned() {
    # Never adopt/stop an unrelated Compose project merely because its name fits.
    for container in $(docker ps -aq --filter "label=com.docker.compose.project=$project"); do
        owner=$(docker inspect -f '{{index .Config.Labels "rvbox.rdp.lan.managed_by"}}|{{index .Config.Labels "rvbox.rdp.lan.profile"}}|{{index .Config.Labels "rvbox.rdp.lan.vm_uuid"}}' "$container")
        [ "$owner" = "test/rdp-access/rdp-access|$profile|$vm_uuid" ] || fail "unowned/mismatched container in project $project"
    done
}
[ ! -L "$dir" ] && [ ! -L "$(dirname "$dir")" ] || fail 'remote state directory is a symlink'
for file in .env .env.new compose.yaml; do [ ! -L "$dir/$file" ] || fail 'remote state file is a symlink'; done
docker info >/dev/null
assert_owned
if [ -f "$dir/.env" ]; then
    saved_uuid=$(sed -n 's/^VM_UUID=//p' "$dir/.env")
    [ -z "$saved_uuid" ] || [ "$saved_uuid" = "$vm_uuid" ] || fail 'saved VM UUID mismatch; select the correct profile/VM identity'
fi

case $action in
    up)
        info=$(VBoxManage showvminfo "$vm" --machinereadable)
        printf '%s\n' "$info" | grep -Fqx "UUID=\"$vm_uuid\"" || fail 'VM UUID mismatch'
        printf '%s\n' "$info" | grep -qx 'VMState="running"' || fail 'VM is not running'
        printf '%s\n' "$info" | grep -qx 'vrde="on"' || fail 'VRDE is disabled'
        printf '%s\n' "$info" | grep -qx 'vrdeaddress="127.0.0.1"' || fail 'expected private loopback VRDE backend'
        printf '%s\n' "$info" | grep -qx "vrdeport=$vrde_port" || fail 'requested backend port does not belong to this VM'
        listener 127.0.0.1 "$vrde_port" || fail 'private VRDE backend is not listening'
        if [ "$bind" = auto ]; then
            bind=$(ip -4 route get 1.1.1.1 | awk '{ for(i=1;i<=NF;i++) if($i=="src") { print $(i+1); exit } }')
        fi
        # Revalidate the detected value before it can become a socat argument.
        printf '%s\n' "$bind" | awk -F. 'NF!=4 { exit 1 } { for(i=1;i<=4;i++) if($i !~ /^[0-9]+$/ || $i+0>255) exit 1; exit !(($1==10)||($1==172&&$2>=16&&$2<=31)||($1==192&&$2==168)) }' || fail 'detected address is not private IPv4; use --lan-bind'
        assigned=$(ip -4 -o addr show scope global | awk -v wanted="$bind" '{ split($4,a,"/"); if(a[1]==wanted) { print $4; exit } }')
        [ -n "$assigned" ] || fail 'LAN bind is not assigned on this host'
        [ "$cidr" != auto ] || cidr=$assigned
        cidr_bits=${cidr##*/}
        case ${cidr%/*} in
            10.*) [ "$cidr_bits" -ge 8 ] || fail 'interface subnet extends outside private 10/8; specify --lan-cidr' ;;
            172.*) [ "$cidr_bits" -ge 12 ] || fail 'interface subnet extends outside private 172.16/12; specify --lan-cidr' ;;
            192.*) [ "$cidr_bits" -ge 16 ] || fail 'interface subnet extends outside private 192.168/16; specify --lan-cidr' ;;
        esac
        # Fail on an occupied unowned listener; never kill it or change firewall.
        if listener "$bind" "$lan_port" && [ -z "$(docker ps -q --filter "label=com.docker.compose.project=$project")" ]; then
            fail 'LAN port already has an unrelated listener; use --lan-port with a free port'
        fi
        umask 077
        mkdir -p "$dir"
        chmod 700 "$dir"
        printf '%s' "$compose_encoded" | base64 -d >"$dir/compose.yaml"
        printf 'LAN_BIND=%s\nLAN_PORT=%s\nLAN_CIDR=%s\nVRDE_PORT=%s\nLAN_PROFILE=%s\nVM_UUID=%s\n' \
            "$bind" "$lan_port" "$cidr" "$vrde_port" "$profile" "$vm_uuid" >"$dir/.env.new"
        mv "$dir/.env.new" "$dir/.env"
        compose config -q
        compose up -d --pull missing
        attempts=0
        while [ "$attempts" -lt 10 ]; do
            relay=$(compose ps -q relay)
            if [ -n "$relay" ] && [ "$(docker inspect -f '{{.State.Running}}' "$relay")" = true ] && listener "$bind" "$lan_port"; then break; fi
            attempts=$((attempts+1)); sleep 1
        done
        [ "$attempts" -lt 10 ] || { compose logs --tail 20 relay; fail 'LAN listener did not become ready'; }
        printf 'lan_endpoint=%s:%s\nlan_allowed_subnet=%s\nlan_backend=127.0.0.1:%s\nlan_project=%s\n' "$bind" "$lan_port" "$cidr" "$vrde_port" "$project"
        printf 'Disconnect the Guacamole desktop before using a native RDP app: VRDE has one console slot.\n'
        ;;
    status)
        printf 'lan_project=%s remote_state=%s\n' "$project" "$dir"
        if [ -f "$dir/.env" ] && [ -f "$dir/compose.yaml" ]; then
            sed -n '/^LAN_BIND=/p; /^LAN_PORT=/p; /^LAN_CIDR=/p; /^VRDE_PORT=/p' "$dir/.env"
            compose ps -a
            saved_bind=$(sed -n 's/^LAN_BIND=//p' "$dir/.env"); saved_port=$(sed -n 's/^LAN_PORT=//p' "$dir/.env")
            if listener "$saved_bind" "$saved_port"; then printf 'lan_listener=active\n'; else printf 'lan_listener=inactive\n'; fi
            saved_backend=$(sed -n 's/^VRDE_PORT=//p' "$dir/.env")
            if listener 127.0.0.1 "$saved_backend"; then printf 'lan_backend=active\n'; else printf 'lan_backend=inactive (VM off or VRDE unavailable)\n'; fi
        else
            printf 'lan_listener=not_configured\n'
            [ -z "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ] || fail 'owned containers remain without configuration; rerun lan-up to recover'
        fi
        ;;
    down|clean)
        if [ -f "$dir/.env" ] && [ -f "$dir/compose.yaml" ]; then
            compose down --remove-orphans
        else
            [ -z "$(docker ps -aq --filter "label=com.docker.compose.project=$project")" ] || fail 'configuration missing while owned containers remain; rerun lan-up, then lan-down'
        fi
        if [ "$action" = clean ]; then
            # Delete only known generated files; unexpected content is retained.
            rm -f "$dir/.env" "$dir/.env.new" "$dir/compose.yaml"
            if [ -d "$dir" ]; then rmdir "$dir" || fail 'unexpected remote state files retained; inspect this exact profile directory'; fi
            if [ "$remove_images" = true ]; then
                docker image rm "$image" || printf 'Relay image retained because it is shared/in use; no force or global prune was used.\n'
            fi
        fi
        printf 'LAN relay stopped; VM, Windows settings, Guacamole and other profiles are unchanged.\n'
        ;;
esac
REMOTE
}
# All four actions converge on the same owned profile. A lost SSH response can
# safely be retried; unlike VM reset/capture, no VM lifecycle mutation occurs.
attempt=1
while [ "$attempt" -le 4 ]; do
    if run_remote; then exit 0; fi
    attempt=$((attempt+1))
    if [ "$attempt" -le 4 ]; then
        printf 'LAN relay action interrupted/failed; retry %s/4\n' "$attempt" >&2
        sleep 2
    fi
done
fail 'LAN relay action failed after four attempts; inspect lan-status and the reported host error'
