#!/bin/bash

# typically do:
#export LEAPMILE_CLOUD_IP
#bash autosshtunnel.sh

if [ -z "${LEAPMILE_CLOUD_IP:-}" ]; then
  echo "LEAPMILE_CLOUD_IP is not set"
  echo "Run, eg: export LEAPMILE_CLOUD_IP='153.15.38.11'"
  exit 1
fi

PUB_KEY="$HOME/.ssh/id_ed25519.pub"
echo $PUB_KEY
if [ ! -f "$PUB_KEY" ]; then
    ssh-keygen -t ed25519 -f "$HOME/.ssh/id_ed25519" -N ""
fi

ssh-copy-id -i "$PUB_KEY" "root@$LEAPMILE_CLOUD_IP"

echo "Installing required packages..."
sudo apt-get update -y
sudo apt-get install -y ssh autossh

# ---------- SSH CONFIG ----------
SSHD_CONFIG="/etc/ssh/sshd_config"
echo "Configuring sshd..."

sudo sed -i \
  -e 's/^#\?PermitRootLogin.*/PermitRootLogin yes/' \
  -e 's/^#\?GatewayPorts.*/GatewayPorts yes/' \
  "$SSHD_CONFIG"

sudo systemctl restart ssh

AUTOSSH_BIN=/usr/bin/autossh
SYSTEMD_DIR=/etc/systemd/system

create_tunnel() {
  local service_name=$1
  local remote_port=$2
  local local_port=$3
  local service_file="${SYSTEMD_DIR}/${service_name}.service"

  if systemctl list-unit-files | grep -q "^${service_name}.service"; then
    echo "${service_name} already exists — skipping"
    return
  fi

  echo "Creating tunnel: ${service_name} (${remote_port} - ${local_port})"

  sudo tee "$service_file" > /dev/null <<EOF
[Unit]
Description=AutoSSH tunnel ${service_name} (${remote_port})
After=network-online.target
Wants=network-online.target

[Service]
User=root
Environment=AUTOSSH_PORT=0
Environment=AUTOSSH_POLL=30
ExecStart=${AUTOSSH_BIN} -N \\
  -o ServerAliveInterval=30 \\
  -o ServerAliveCountMax=3 \\
  -o ExitOnForwardFailure=yes \\
  -R 0.0.0.0:${remote_port}:localhost:${local_port} \\
  root@${LEAPMILE_CLOUD_IP}

Restart=always
RestartSec=10
StartLimitIntervalSec=0

[Install]
WantedBy=multi-user.target
EOF

  sudo systemctl daemon-reload
  sudo systemctl enable --now "$service_name"
}

echo "Deploying AutoSSH tunnels..."

create_tunnel autossh_tunnel 2222 22
create_tunnel pgadmin_tunnel 25061 25060
create_tunnel services_tunnel 443 443
create_tunnel mosquitto_tunnel 1883 1883

sudo systemctl daemon-reload

echo ""
echo "All tunnels deployed. Current status:"
systemctl status autossh_tunnel pgadmin_tunnel services_tunnel mosquitto_tunnel --no-pager
