#!/usr/bin/env bash
# Saywire SSH bastion setup. Run it on the bastion (a Linux host with OpenSSH that can reach your database).
#
#   curl -fsSL https://saywire.dev/scripts/bastion.sh | sudo bash -s -- --key 'ssh-ed25519 AAAA… saywire-my-server' --allow 10.0.1.5:5432
#
# It creates a tunnel-only user (no password, no shell, no TTY) whose key can only open TCP forwards to the
# targets you allow, adds an sshd drop-in that enforces the same, checks the targets are reachable, and prints the
# host key fingerprints to compare in the Saywire dashboard. Safe to run again (it replaces the key and targets).
# Manual setup and how it works: https://saywire.dev/docs/ssh-bastion
set -euo pipefail

VERSION="1"
TUNNEL_USER="saywire"
KEY=""
FROM=""
ALLOW=()
DRY_RUN=0
UNINSTALL=0
MARKER="Saywire SSH tunnel"
DROPIN="/etc/ssh/sshd_config.d/saywire.conf"

usage() {
  cat <<'EOF'
Usage: bastion.sh --key '<public key>' --allow <host:port> [--allow <host:port> ...] [options]

  --key '<public key>'   The public key from the Saywire dashboard (ssh-ed25519 …). Required.
  --allow <host:port>    A database the tunnel may reach, as this machine sees it (e.g. 10.0.1.5:5432,
                         db.internal:5432, 127.0.0.1:5432). Repeat for several. Required.
  --user <name>          Tunnel user to create (default: saywire). Must match "SSH user" in the dashboard.
  --from <ip[,ip...]>    Only accept the key from these addresses or CIDRs (e.g. Saywire's egress IP).
  --dry-run              Print what would change, change nothing.
  --uninstall            Remove the tunnel user and the sshd drop-in.
  -h, --help             Show this help.
EOF
}

say() { printf '\033[1m%s\033[0m\n' "$*"; }
ok() { printf '  \033[32m✓\033[0m %s\n' "$*"; }
warn() { printf '  \033[33m!\033[0m %s\n' "$*" >&2; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
run() { if [ "$DRY_RUN" = 1 ]; then printf '  + %s\n' "$*"; else "$@"; fi; }
write_file() { # write_file <path> <mode> <owner> <content>
  if [ "$DRY_RUN" = 1 ]; then printf '  + write %s (mode %s, owner %s):\n%s\n' "$1" "$2" "$3" "$(printf '%s\n' "$4" | sed 's/^/      /')"; return; fi
  local tmp; tmp="$(mktemp)"
  printf '%s\n' "$4" >"$tmp"
  install -m "$2" -o "${3%%:*}" -g "${3##*:}" "$tmp" "$1"
  rm -f "$tmp"
}

while [ $# -gt 0 ]; do
  case "$1" in
    --key) KEY="${2:-}"; shift 2 ;;
    --allow) ALLOW+=("${2:-}"); shift 2 ;;
    --user) TUNNEL_USER="${2:-}"; shift 2 ;;
    --from) FROM="${2:-}"; shift 2 ;;
    --dry-run) DRY_RUN=1; shift ;;
    --uninstall) UNINSTALL=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) usage >&2; die "unknown option: $1" ;;
  esac
done

[[ "$TUNNEL_USER" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || die "--user must be a lowercase Unix user name"
[ "$(uname -s)" = "Linux" ] || die "run this on the Linux bastion host"
if [ "$DRY_RUN" = 0 ] && [ "$(id -u)" != 0 ]; then die "run as root (pipe into 'sudo bash'), or add --dry-run"; fi

SSHD="$(command -v sshd || true)"; [ -n "$SSHD" ] || SSHD=/usr/sbin/sshd
[ -x "$SSHD" ] || die "OpenSSH server (sshd) isn't installed"
NOLOGIN="$(command -v nologin || true)"
for c in /usr/sbin/nologin /sbin/nologin; do [ -n "$NOLOGIN" ] || { [ -x "$c" ] && NOLOGIN="$c"; }; done
[ -n "$NOLOGIN" ] || NOLOGIN=/bin/false

reload_sshd() {
  if [ "$DRY_RUN" = 1 ]; then printf '  + reload sshd\n'; return; fi
  systemctl reload ssh 2>/dev/null || systemctl reload sshd 2>/dev/null || service ssh reload 2>/dev/null || service sshd reload 2>/dev/null ||
    warn "couldn't reload sshd; restart it yourself (existing sessions stay open)"
}

ours() { [ "$(getent passwd "$TUNNEL_USER" | cut -d: -f5)" = "$MARKER" ]; }

if [ "$UNINSTALL" = 1 ]; then
  say "Removing the Saywire tunnel"
  if getent passwd "$TUNNEL_USER" >/dev/null; then
    ours || die "user '$TUNNEL_USER' wasn't created by this script; not touching it"
    run pkill -u "$TUNNEL_USER" || true
    run userdel -r "$TUNNEL_USER"
    ok "removed user $TUNNEL_USER"
  else
    ok "no user $TUNNEL_USER"
  fi
  if [ -f "$DROPIN" ]; then run rm -f "$DROPIN"; reload_sshd; ok "removed $DROPIN"; fi
  exit 0
fi

[ -n "$KEY" ] || { usage >&2; die "--key is required (copy it from the dashboard)"; }
[[ "$KEY" =~ ^(ssh-ed25519|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ssh-rsa)\ [A-Za-z0-9+/]+=*(\ [A-Za-z0-9@._-]+)?$ ]] ||
  die "--key doesn't look like one public key line (ssh-ed25519 AAAA… comment)"
[ "${#ALLOW[@]}" -gt 0 ] || { usage >&2; die "--allow is required: the database host:port as this machine sees it"; }
for t in "${ALLOW[@]}"; do
  [[ "$t" =~ ^([A-Za-z0-9.-]+|\[[0-9A-Fa-f:]+\]):[0-9]{1,5}$ ]] || die "--allow '$t' must be host:port (IPv6 as [addr]:port)"
done
[ -z "$FROM" ] || [[ "$FROM" =~ ^[0-9A-Fa-f.:/,]+$ ]] || die "--from must be IPs or CIDRs, comma-separated"

if [ "$DRY_RUN" = 1 ]; then say "Saywire bastion setup v$VERSION (dry run: nothing changes)"; else say "Saywire bastion setup v$VERSION"; fi

# 1. Tunnel-only user: no password ('*' = no password login, but not "locked", which sshd would refuse), no shell.
if getent passwd "$TUNNEL_USER" >/dev/null; then
  ours || die "user '$TUNNEL_USER' already exists and wasn't created by this script; pick another with --user"
  ok "user $TUNNEL_USER exists"
else
  run useradd --create-home --shell "$NOLOGIN" --comment "$MARKER" "$TUNNEL_USER"
  ok "created user $TUNNEL_USER (shell $NOLOGIN)"
fi
run usermod -p '*' "$TUNNEL_USER"
HOME_DIR="$(getent passwd "$TUNNEL_USER" | cut -d: -f6 || true)"; HOME_DIR="${HOME_DIR:-/home/$TUNNEL_USER}"

# 2. The key, restricted to port forwarding to the allowed targets only.
OPTS="restrict,port-forwarding"
for t in "${ALLOW[@]}"; do OPTS="$OPTS,permitopen=\"$t\""; done
[ -z "$FROM" ] || OPTS="$OPTS,from=\"$FROM\""
run install -d -m 700 -o "$TUNNEL_USER" -g "$(id -gn "$TUNNEL_USER" 2>/dev/null || echo "$TUNNEL_USER")" "$HOME_DIR/.ssh"
write_file "$HOME_DIR/.ssh/authorized_keys" 600 "$TUNNEL_USER:$(id -gn "$TUNNEL_USER" 2>/dev/null || echo "$TUNNEL_USER")" "$OPTS $KEY"
ok "installed the key (forwarding only, to: ${ALLOW[*]})"

# 3. sshd drop-in enforcing the same for this user, whatever the key line says.
if grep -Eqs '^[[:space:]]*Include[[:space:]]+/etc/ssh/sshd_config\.d/\*\.conf' /etc/ssh/sshd_config; then
  DROPIN_BODY="# Managed by https://saywire.dev/scripts/bastion.sh (v$VERSION). Remove with: bastion.sh --uninstall
Match User $TUNNEL_USER
    AllowTcpForwarding local
    PermitOpen ${ALLOW[*]}
    PasswordAuthentication no
    KbdInteractiveAuthentication no
    PermitTTY no
    X11Forwarding no
    AllowAgentForwarding no
    AllowStreamLocalForwarding no
    PermitTunnel no
    GatewayPorts no
    ForceCommand $NOLOGIN"
  had_dropin=0; [ -f "$DROPIN" ] && had_dropin=1 && cp "$DROPIN" "$DROPIN.bak"
  write_file "$DROPIN" 644 "root:root" "$DROPIN_BODY"
  check="$(mktemp)"
  if [ "$DRY_RUN" = 0 ] && ! "$SSHD" -t 2>"$check"; then
    if [ "$had_dropin" = 1 ]; then mv "$DROPIN.bak" "$DROPIN"; else rm -f "$DROPIN"; fi
    cat "$check" >&2
    die "sshd rejected the drop-in; nothing was reloaded and your SSH config is unchanged"
  fi
  rm -f "$check"
  rm -f "$DROPIN.bak"
  reload_sshd
  ok "sshd drop-in $DROPIN (forwarding only, no TTY, no shell)"
else
  warn "/etc/ssh/sshd_config has no 'Include /etc/ssh/sshd_config.d/*.conf'; skipped the drop-in (the key options still restrict it)"
fi

if [ "$DRY_RUN" = 0 ]; then
  fwd="$("$SSHD" -T -C "user=$TUNNEL_USER,host=saywire,addr=127.0.0.1" 2>/dev/null | awk '$1=="allowtcpforwarding"{print $2}')"
  case "$fwd" in
    no|remote) die "sshd has AllowTcpForwarding $fwd for $TUNNEL_USER; allow 'local' forwarding for this user" ;;
    "") warn "couldn't read sshd's effective settings; check AllowTcpForwarding isn't 'no'" ;;
    *) ok "sshd allows local forwarding for $TUNNEL_USER" ;;
  esac
fi

# 4. Can this machine reach the targets?
for t in "${ALLOW[@]}"; do
  host="${t%:*}"; port="${t##*:}"; host="${host#[}"; host="${host%]}"
  if timeout 3 bash -c "exec 3<>/dev/tcp/$host/$port" 2>/dev/null; then ok "reached $t"; else warn "can't reach $t from here yet (firewall, security group or wrong host?)"; fi
done

# 5. What to paste or compare in the dashboard.
say "Host key fingerprints (compare with the dashboard before you click Trust)"
for k in /etc/ssh/ssh_host_*_key.pub; do [ -f "$k" ] && ssh-keygen -lf "$k" | sed 's/^/  /'; done
say "Next, in the Saywire dashboard"
port="$("$SSHD" -T 2>/dev/null | awk '$1=="port"{print $2; exit}' || true)"
echo "  Bastion host: this machine's public IP or DNS name, port ${port:-22}, user $TUNNEL_USER"
echo "  Connection string: use the database host exactly as allowed above (e.g. postgres://user:pass@${ALLOW[0]}/db)"
echo "  Then: Test connections → compare the fingerprint → Trust → Test again."
