#!/usr/bin/env bash
# Corrected relay finish: put the onion config DIRECTLY in torrc (no glob include), reset Tor's
# failure counter, start cleanly, install the relay service + key, self-test. Plus security tidy:
# lock root SSH OFF, confirm UFW + fail2ban allow-list.
set -uo pipefail
ONION_DIR=/var/lib/tor/pvtcoms-relay
PORT=9911
BIN_SRC=/root/pvtcoms-deploy/pvtcoms-relay
BIN_DST=/usr/local/bin/pvtcoms-relay
ENVF=/etc/pvtcoms-relay.env
SERVICE=/etc/systemd/system/pvtcoms-relay.service
log(){ printf '\033[1;36m[finish2]\033[0m %s\n' "$*"; }

# --- 1. Repair Tor config: drop the broken glob include + drop-in, use direct config in torrc ---
sed -i '/^%include .*torrc\.d/d' /etc/tor/torrc
rm -f /etc/tor/torrc.d/pvtcoms.conf
if ! grep -q "HiddenServiceDir ${ONION_DIR}" /etc/tor/torrc; then
  cat >> /etc/tor/torrc <<EOF

# pvtcoms relay onion service
HiddenServiceDir ${ONION_DIR}
HiddenServicePort ${PORT} 127.0.0.1:${PORT}
EOF
fi

# --- 2. Clear the failed/rate-limited state and start the REAL tor instance cleanly ---
systemctl reset-failed tor@default 2>/dev/null || true
systemctl enable tor@default >/dev/null 2>&1 || true
# validate config first so we fail fast with a clear message
if ! tor --defaults-torrc /usr/share/tor/tor-service-defaults-torrc -f /etc/tor/torrc --verify-config >/tmp/torverify 2>&1; then
  log "Tor config INVALID:"; cat /tmp/torverify; exit 1
fi
systemctl restart tor@default
log "waiting for the onion hostname (up to 120s)…"
for _ in $(seq 1 60); do [ -f "${ONION_DIR}/hostname" ] && break; sleep 2; done
if [ ! -f "${ONION_DIR}/hostname" ]; then
  log "ERROR: onion still not generated. Diagnostics:"
  systemctl --no-pager --full status tor@default 2>/dev/null | head -12
  journalctl -u tor@default -n 20 --no-pager 2>/dev/null | tail -20
  exit 1
fi
chmod 700 "${ONION_DIR}" 2>/dev/null || true
log "onion ready: $(cat ${ONION_DIR}/hostname)"

# --- 3. Relay binary + access key + sandboxed systemd service ---
install -m755 "$BIN_SRC" "$BIN_DST"
id pvtcoms-relay &>/dev/null || useradd --system --no-create-home --shell /usr/sbin/nologin pvtcoms-relay
install -d -m700 -o pvtcoms-relay -g pvtcoms-relay /var/lib/pvtcoms-relay
if [ ! -f "$ENVF" ]; then
  cat > "$ENVF" <<EOF
PVTCOMS_RELAY_KEY=$(openssl rand -hex 32)
PVTCOMS_RELAY_POW=20
PVTCOMS_RELAY_TTL=1209600
PVTCOMS_RELAY_DATA=/var/lib/pvtcoms-relay/store.bin
EOF
  chmod 600 "$ENVF"
fi
cat > "$SERVICE" <<EOF
[Unit]
Description=pvtcoms oblivious relay (localhost; reached via Tor onion)
After=network-online.target tor@default.service
Wants=network-online.target
[Service]
Type=simple
User=pvtcoms-relay
Group=pvtcoms-relay
EnvironmentFile=${ENVF}
ExecStart=${BIN_DST} relay 127.0.0.1:${PORT}
Restart=on-failure
RestartSec=3
StateDirectory=pvtcoms-relay
WorkingDirectory=/var/lib/pvtcoms-relay
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
IPAddressAllow=localhost
IPAddressDeny=any
ReadWritePaths=/var/lib/pvtcoms-relay
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now pvtcoms-relay
sleep 2

# --- 4. Security tidy: lock root SSH OFF (remove the bootstrap drop-in so harden's 'no' wins) ---
rm -f /etc/ssh/sshd_config.d/00-pvtcoms-bootstrap.conf
sshd -t && systemctl restart ssh && log "root SSH login disabled (admin via pvtops only)."

# --- 5. End-to-end self-test through the running relay ---
KEY="$(grep '^PVTCOMS_RELAY_KEY=' "$ENVF" | cut -d= -f2)"
POW="$(grep '^PVTCOMS_RELAY_POW=' "$ENVF" | cut -d= -f2)"
PVTCOMS_RELAY_KEY="$KEY" PVTCOMS_RELAY_POW="$POW" "$BIN_DST" send "127.0.0.1:${PORT}" "__selftest__" "relay selftest ok" >/dev/null 2>&1
OUT="$(PVTCOMS_RELAY_KEY="$KEY" PVTCOMS_RELAY_POW="$POW" "$BIN_DST" recv "127.0.0.1:${PORT}" "__selftest__" 2>/dev/null)"
echo "$OUT" | grep -q "relay selftest ok" && ST="PASS ✓" || ST="FAIL ✗"

# --- 6. Summary (incl. security answers) ---
echo
echo "==================== pvtcoms RELAY — READY ===================="
echo " relay:        $(systemctl is-active pvtcoms-relay)    tor: $(systemctl is-active tor@default)"
echo " self-test:    $ST   (deposit + pull round-trip via access key + PoW)"
echo " firewall:     $(ufw status | head -1)  — inbound:"
ufw status | grep -E '22|ALLOW' | sed 's/^/                /'
echo " fail2ban:     $(systemctl is-active fail2ban); ignoreip = $(grep -h ignoreip /etc/fail2ban/jail.d/*.local 2>/dev/null | head -1 | cut -d= -f2- | xargs)"
echo " root SSH:     $(sshd -T 2>/dev/null | grep -i '^permitrootlogin' | awk '{print $2}')   (password auth: $(sshd -T 2>/dev/null | grep -i '^passwordauthentication' | awk '{print $2}'))"
echo " admin access: pvtops (key + sudo);  root = Contabo console only"
echo
echo " RELAY ONION (bake into the app as the relay):"
echo "     $(cat ${ONION_DIR}/hostname)"
echo " ACCESS KEY (give to invited members only):"
echo "     ${KEY}"
echo "=============================================================="
[ "$ST" = "PASS ✓" ]
