#!/usr/bin/env bash
# ottervpn server installer — turns a fresh Ubuntu/Debian/Fedora VPS into an ottervpn location.
# Usage: curl -fsSL https://holtvpn.co/install.sh | sudo bash -s -- <node-token>
set -euo pipefail
API="https://holtvpn.co"
TOKEN="${1:-${OTTER_TOKEN:-}}"
PORT="${PORT:-51820}"

say() { printf '\033[1;36m==>\033[0m %s\n' "$*"; }
die() { printf '\033[1;31mError:\033[0m %s\n' "$*" >&2; exit 1; }

[ -n "$TOKEN" ] || die "missing node token. Copy the full command from Servers in your ottervpn dashboard."
[ "$(id -u)" -eq 0 ] || die "run as root (put sudo before bash)."

say "Installing WireGuard"
if command -v apt-get >/dev/null 2>&1; then
  export DEBIAN_FRONTEND=noninteractive
  apt-get update -y -qq
  apt-get install -y -qq wireguard-tools iptables python3 curl iproute2 >/dev/null
elif command -v dnf >/dev/null 2>&1; then
  dnf install -y -q wireguard-tools iptables python3 curl iproute
else
  die "unsupported system. Use Ubuntu 22.04/24.04, Debian 12 or Fedora."
fi

WAN=$(ip -4 route show default | awk '{print $5; exit}')
[ -n "$WAN" ] || die "could not find the public network interface."

say "Creating server keys"
mkdir -p /etc/wireguard /etc/ottervpn
chmod 700 /etc/wireguard /etc/ottervpn
[ -f /etc/wireguard/ottervpn.key ] || (umask 077 && wg genkey > /etc/wireguard/ottervpn.key)
PRIV=$(cat /etc/wireguard/ottervpn.key)
PUB=$(printf '%s' "$PRIV" | wg pubkey)

say "Configuring wg0 on UDP $PORT (exit via $WAN)"
umask 077
cat > /etc/wireguard/wg0.conf <<EOF
[Interface]
Address = 10.66.0.1/16
ListenPort = $PORT
PrivateKey = $PRIV
PostUp = iptables -t nat -A POSTROUTING -s 10.66.0.0/16 -o $WAN -j MASQUERADE; iptables -I FORWARD -i %i -o %i -j DROP; iptables -A FORWARD -i %i -o $WAN -j ACCEPT; iptables -A FORWARD -i $WAN -o %i -m state --state RELATED,ESTABLISHED -j ACCEPT; iptables -t mangle -A FORWARD -o %i -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
PostDown = iptables -t nat -D POSTROUTING -s 10.66.0.0/16 -o $WAN -j MASQUERADE; iptables -D FORWARD -i %i -o %i -j DROP; iptables -D FORWARD -i %i -o $WAN -j ACCEPT; iptables -D FORWARD -i $WAN -o %i -m state --state RELATED,ESTABLISHED -j ACCEPT; iptables -t mangle -D FORWARD -o %i -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu
EOF

echo 'net.ipv4.ip_forward=1' > /etc/sysctl.d/99-ottervpn.conf
sysctl -q -p /etc/sysctl.d/99-ottervpn.conf

if command -v ufw >/dev/null 2>&1 && ufw status | grep -q active; then
  ufw allow "$PORT"/udp >/dev/null
  ufw route allow in on wg0 out on "$WAN" >/dev/null || true
fi
if command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
  firewall-cmd -q --permanent --add-port="$PORT"/udp && firewall-cmd -q --permanent --add-masquerade && firewall-cmd -q --reload
fi

systemctl enable -q wg-quick@wg0
systemctl restart wg-quick@wg0

say "Registering with $API"
RESP=$(curl -4 -fsS -X POST "$API/api/node/register" \
  -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d "{\"pubkey\":\"$PUB\",\"port\":$PORT}") || die "registration failed. Check that the token is current."
NODE_ID=$(printf '%s' "$RESP" | python3 -c 'import sys,json;print(json.load(sys.stdin)["id"])')

cat > /etc/ottervpn/agent.env <<EOF
OTTER_API=$API
OTTER_TOKEN=$TOKEN
OTTER_NODE=$NODE_ID
OTTER_IFACE=wg0
EOF

say "Installing the sync agent"
curl -fsS "$API/agent.py" -o /usr/local/bin/ottervpn-agent
chmod 755 /usr/local/bin/ottervpn-agent
cat > /etc/systemd/system/ottervpn-agent.service <<EOF
[Unit]
Description=ottervpn peer sync agent
After=network-online.target wg-quick@wg0.service
Wants=network-online.target

[Service]
EnvironmentFile=/etc/ottervpn/agent.env
ExecStart=/usr/bin/python3 /usr/local/bin/ottervpn-agent
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable -q --now ottervpn-agent
systemctl restart ottervpn-agent

say "Done. This server is live as $NODE_ID."
echo "    Make sure UDP $PORT is open in your hosting provider's firewall."
echo "    Logs: journalctl -u ottervpn-agent -f"
