#!/bin/bash
# Meowlix SSH tunnel: gives this VPS a public SSH address on ssh.meowlix.sh.
# Usage: bash <(curl -fsSL https://ssh.meowlix.sh)
set -e

RELAY=ssh.meowlix.sh
RELAY_PORT=2200
DIR=/etc/meowlix-tunnel
G='\033[0;32m'; R='\033[0;31m'; Y='\033[1;33m'; C='\033[0;36m'; N='\033[0m'

die() { echo -e "${R}x $*${N}"; exit 1; }
[ "$(id -u)" = 0 ] || die "Run this as root."
command -v systemctl >/dev/null && [ -d /run/systemd/system ] || die "This VPS has no systemd, which the tunnel needs."

echo -e "${C}> Installing SSH server...${N}"
if ! command -v sshd >/dev/null || ! command -v ssh >/dev/null || ! command -v curl >/dev/null; then
    if command -v apt-get >/dev/null; then
        export DEBIAN_FRONTEND=noninteractive
        apt-get update -qq || true
        apt-get install -y -qq openssh-server openssh-client curl >/dev/null
    elif command -v dnf >/dev/null; then dnf install -y -q openssh-server openssh-clients curl
    elif command -v yum >/dev/null; then yum install -y -q openssh-server openssh-clients curl
    elif command -v apk >/dev/null; then apk add -q openssh curl
    else die "Unsupported OS: install openssh-server yourself and re-run."
    fi
fi

echo -e "${C}> Enabling root password login...${N}"
mkdir -p /etc/ssh/sshd_config.d
grep -qE '^\s*Include\s+/etc/ssh/sshd_config.d/' /etc/ssh/sshd_config \
    || sed -i '1i Include /etc/ssh/sshd_config.d/*.conf' /etc/ssh/sshd_config
cat > /etc/ssh/sshd_config.d/00-meowlix.conf <<'EOF'
PermitRootLogin yes
PasswordAuthentication yes
KbdInteractiveAuthentication yes
EOF
sshd -t || die "sshd config check failed."
systemctl enable ssh >/dev/null 2>&1 || systemctl enable sshd >/dev/null 2>&1 || true
systemctl restart ssh 2>/dev/null || systemctl restart sshd

if passwd -S root 2>/dev/null | awk '{exit !($2=="L"||$2=="NP")}'; then
    echo -e "${Y}! root has no password yet. Set one now; you will log in with it.${N}"
    until passwd root </dev/tty; do echo -e "${Y}Try again.${N}"; done
fi

echo -e "${C}> Registering this VPS...${N}"
mkdir -p "$DIR"; chmod 700 "$DIR"
[ -f "$DIR/id_ed25519" ] || ssh-keygen -q -t ed25519 -N '' -C "meowlix-$(hostname)" -f "$DIR/id_ed25519"
curl -fsS "https://$RELAY/known_hosts" -o "$DIR/known_hosts" || die "Could not reach $RELAY."
KEY=$(cut -d' ' -f1,2 "$DIR/id_ed25519.pub")
NAME=$(hostname | tr -cd 'A-Za-z0-9._-' | cut -c1-64)
RESP=$(curl -sS -w '\n%{http_code}' -X POST -H 'Content-Type: application/json' \
    --data "{\"key\":\"$KEY\",\"name\":\"$NAME\"}" "https://$RELAY/register") || die "Registration failed."
CODE=$(echo "$RESP" | tail -n1); BODY=$(echo "$RESP" | sed '$d')
[ "$CODE" = 200 ] || die "Registration refused: $BODY"
PORT=$(echo "$BODY" | grep -oE '"port": *[0-9]+' | grep -oE '[0-9]+$')
[ -n "$PORT" ] || die "Unexpected reply: $BODY"
echo "$PORT" > "$DIR/port"

cat > /etc/systemd/system/meowlix-tunnel.service <<EOF
[Unit]
Description=Meowlix SSH tunnel ($RELAY:$PORT -> local SSH)
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=/usr/bin/ssh -N -T -o ExitOnForwardFailure=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$DIR/known_hosts -o HostKeyAlias=$RELAY -i $DIR/id_ed25519 -p $RELAY_PORT -R 0.0.0.0:$PORT:127.0.0.1:22 vps@$RELAY
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable meowlix-tunnel >/dev/null 2>&1
systemctl restart meowlix-tunnel
sleep 4
systemctl is-active --quiet meowlix-tunnel || die "Tunnel did not start: journalctl -u meowlix-tunnel"

echo
echo -e "${G}Done. Your VPS is reachable at:${N}"
echo
echo -e "  Host: ${Y}$RELAY${N}"
echo -e "  Port: ${Y}$PORT${N}"
echo -e "  User: ${Y}root${N}"
echo
echo -e "  ssh root@$RELAY -p $PORT"
echo
echo -e "In Termius: New Host -> Address ${Y}$RELAY${N}, Port ${Y}$PORT${N}, Username root, your root password."
