#!/usr/bin/env bash
set -e

echo "VPS Bootstrap Starting..."

############################
# CONFIG
############################
NEW_USER="dev"
GITHUB_USER="Bijit-Mondal"
SSH_PORT="22"

############################
# CHECK ROOT
############################
if [ "$EUID" -ne 0 ]; then
  echo "❌ Run as root"
  exit 1
fi

############################
# SYSTEM UPDATE
############################
echo "📦 Updating system..."
apt update && apt upgrade -y

apt install -y \
  curl \
  git \
  sudo \
  ufw \
  ca-certificates \
  gnupg \
  lsb-release

############################
# CREATE NON-ROOT USER
############################
echo "👤 Creating user..."

if ! id "$NEW_USER" >/dev/null 2>&1; then
  adduser --disabled-password --gecos "" $NEW_USER
fi

usermod -aG sudo $NEW_USER

############################
# SSH KEY SETUP (FROM GITHUB)
############################
echo "🔑 Importing SSH keys from GitHub..."

mkdir -p /home/$NEW_USER/.ssh

curl -fsSL https://github.com/$GITHUB_USER.keys \
  >> /home/$NEW_USER/.ssh/authorized_keys

chmod 700 /home/$NEW_USER/.ssh
chmod 600 /home/$NEW_USER/.ssh/authorized_keys
chown -R $NEW_USER:$NEW_USER /home/$NEW_USER/.ssh

############################
# INSTALL DOCKER
############################
echo "🐳 Installing Docker..."

curl -fsSL https://get.docker.com | sh

systemctl enable docker
systemctl start docker

usermod -aG docker $NEW_USER

############################
# INSTALL DOKPLOY
############################
echo "⚡ Installing Dokploy..."

curl -sSL https://dokploy.com/install.sh | bash

############################
# FIREWALL CONFIG
############################
echo "🔥 Configuring firewall..."

ufw default deny incoming
ufw default allow outgoing

ufw allow ${SSH_PORT}/tcp
ufw allow 80/tcp
ufw allow 443/tcp

ufw --force enable

############################
# SSH HARDENING
############################
echo "🔒 Hardening SSH..."

sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config || true
sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config || true

sed -i 's/PermitRootLogin yes/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config || true

systemctl restart ssh

############################
# BASIC HEALTH ENDPOINT (FOR KENER)
############################
echo "❤️ Creating health endpoint..."

mkdir -p /opt/health
echo "OK" > /opt/health/index.html

docker run -d \
  --name healthcheck \
  -p 127.0.0.1:8080:80 \
  -v /opt/health:/usr/share/nginx/html:ro \
  --restart unless-stopped \
  nginx

############################
# CLEANUP
############################
apt autoremove -y

SERVER_IP=$(curl -s ifconfig.me)

############################
# DONE
############################
echo ""
echo "✅ VPS READY!"
echo ""
echo "Login:"
echo "ssh $NEW_USER@$SERVER_IP"
echo ""
echo "Dokploy Dashboard:"
echo "http://$SERVER_IP"
echo ""
echo "Kener Health Check URL:"
echo "http://$SERVER_IP (or your domain)"
echo ""
echo "🎉 Bootstrap Complete"
