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

SSH_USER="${1:-}"
KEYCLOAK_PORT="${2:-}"

fail() { echo "ERROR: $*" >&2; exit 1; }

[[ ${EUID:-$(id -u)} -eq 0 ]] || fail "Run with sudo or as root."
[[ "$SSH_USER" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || fail "Usage: $0 <ssh-user> <keycloak-port>"
id "$SSH_USER" >/dev/null 2>&1 || fail "SSH user does not exist: $SSH_USER"
[[ "$KEYCLOAK_PORT" =~ ^[0-9]+$ ]] || fail "Keycloak port must be numeric."
(( KEYCLOAK_PORT >= 1 && KEYCLOAK_PORT <= 65535 )) || fail "Keycloak port must be 1-65535."

SSHD_BIN="$(command -v sshd || true)"
[[ -n "$SSHD_BIN" ]] || fail "OpenSSH sshd was not found."
MAIN_CONFIG="/etc/ssh/sshd_config"
DROPIN_DIR="/etc/ssh/sshd_config.d"
[[ -f "$MAIN_CONFIG" ]] || fail "Missing $MAIN_CONFIG"
if ! grep -Eq '^[[:space:]]*Include[[:space:]]+.*sshd_config[.]d/[*][.]conf' "$MAIN_CONFIG"; then
  fail "$DROPIN_DIR/*.conf is not included by sshd_config; configure this host manually."
fi

SERVICE=""
for candidate in sshd ssh; do
  if systemctl is-active --quiet "$candidate"; then SERVICE="$candidate"; break; fi
done
[[ -n "$SERVICE" ]] || fail "No active ssh or sshd systemd unit was found."

install -d -m 0755 "$DROPIN_DIR"
CONFIG="$DROPIN_DIR/60-asl-keycloak-forwarding-${SSH_USER}.conf"
BACKUP=""
if [[ -f "$CONFIG" ]]; then
  BACKUP="${CONFIG}.bak.$(date -u +%Y%m%dT%H%M%SZ)"
  cp -p "$CONFIG" "$BACKUP"
fi

restore() {
  if [[ -n "$BACKUP" && -f "$BACKUP" ]]; then
    mv -f "$BACKUP" "$CONFIG"
  else
    rm -f "$CONFIG"
  fi
}

cat >"$CONFIG" <<EOF
# Managed by ASL Keycloak Console help script.
Match User $SSH_USER
    AllowTcpForwarding local
    AllowStreamLocalForwarding no
    PermitOpen 127.0.0.1:$KEYCLOAK_PORT
    GatewayPorts no
    AllowAgentForwarding no
    X11Forwarding no
    PermitTunnel no
Match All
EOF
chmod 0644 "$CONFIG"

if ! "$SSHD_BIN" -t; then
  restore
  fail "sshd rejected the configuration; the previous state was restored."
fi

EFFECTIVE="$("$SSHD_BIN" -T -C user="$SSH_USER",host=localhost,addr=127.0.0.1,laddr=127.0.0.1,lport=22)"
grep -qx 'allowtcpforwarding local' <<<"$EFFECTIVE" || {
  restore
  fail "Local forwarding is overridden elsewhere; the previous state was restored."
}
grep -qx "permitopen 127.0.0.1:$KEYCLOAK_PORT" <<<"$EFFECTIVE" || {
  restore
  fail "PermitOpen is overridden elsewhere; the previous state was restored."
}

if ! systemctl reload "$SERVICE"; then
  restore
  "$SSHD_BIN" -t || true
  systemctl reload "$SERVICE" || true
  fail "SSH reload failed; the previous state was restored."
fi

echo "Enabled local SSH forwarding for $SSH_USER to 127.0.0.1:$KEYCLOAK_PORT only."
echo "Keep this session open and test a new ASL Keycloak Console connection now."
echo "Configuration: $CONFIG"
[[ -z "$BACKUP" ]] || echo "Previous configuration backup: $BACKUP"
