#!/bin/bash
# =============================================================================
# Server Setup Script for Aurora Production Deployment
# =============================================================================
# Run this script ONCE on a fresh server to configure security settings.
# Usage: sudo bash setup-server.sh
# =============================================================================

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   Aurora Server Security Setup Script    ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then
  echo -e "${RED}Error: Please run as root (sudo)${NC}"
  exit 1
fi

# =============================================================================
# 1. Create Deploy User
# =============================================================================
echo -e "${YELLOW}[1/5] Creating deploy user...${NC}"

DEPLOY_USER="deploy"

if id "$DEPLOY_USER" &>/dev/null; then
  echo -e "  User '$DEPLOY_USER' already exists, skipping..."
else
  adduser --disabled-password --gecos "" $DEPLOY_USER
  echo -e "  ${GREEN}✓${NC} Created user '$DEPLOY_USER'"
fi

# Add to docker group
usermod -aG docker $DEPLOY_USER 2>/dev/null || groupadd docker && usermod -aG docker $DEPLOY_USER
echo -e "  ${GREEN}✓${NC} Added '$DEPLOY_USER' to docker group"

# Add to sudo group (optional - remove if you don't want sudo access)
usermod -aG sudo $DEPLOY_USER
echo -e "  ${GREEN}✓${NC} Added '$DEPLOY_USER' to sudo group"

# Copy SSH keys from root to deploy user
if [ -d /root/.ssh ]; then
  mkdir -p /home/$DEPLOY_USER/.ssh
  cp /root/.ssh/authorized_keys /home/$DEPLOY_USER/.ssh/ 2>/dev/null || true
  chown -R $DEPLOY_USER:$DEPLOY_USER /home/$DEPLOY_USER/.ssh
  chmod 700 /home/$DEPLOY_USER/.ssh
  chmod 600 /home/$DEPLOY_USER/.ssh/authorized_keys 2>/dev/null || true
  echo -e "  ${GREEN}✓${NC} Copied SSH keys to '$DEPLOY_USER'"
fi

# =============================================================================
# 2. Configure UFW Firewall
# =============================================================================
echo -e "${YELLOW}[2/5] Configuring UFW firewall...${NC}"

apt-get update -qq
apt-get install -y -qq ufw

ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
# Add more rules as needed:
# ufw allow 80/tcp   # HTTP
# ufw allow 443/tcp  # HTTPS

# Enable UFW (non-interactive)
echo "y" | ufw enable
echo -e "  ${GREEN}✓${NC} UFW firewall enabled and configured"

# =============================================================================
# 3. Install and Configure Fail2ban
# =============================================================================
echo -e "${YELLOW}[3/5] Installing fail2ban...${NC}"

apt-get install -y -qq fail2ban

# Create local jail configuration
cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime = 1h
findtime = 10m
maxretry = 5

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 24h
EOF

systemctl enable fail2ban
systemctl restart fail2ban
echo -e "  ${GREEN}✓${NC} Fail2ban installed and configured"

# =============================================================================
# 4. Harden SSH Configuration
# =============================================================================
echo -e "${YELLOW}[4/5] Hardening SSH configuration...${NC}"

SSHD_CONFIG="/etc/ssh/sshd_config"

# Backup original config
cp $SSHD_CONFIG ${SSHD_CONFIG}.backup

# Apply hardening settings
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin no/' $SSHD_CONFIG
sed -i 's/^#\?PasswordAuthentication.*/PasswordAuthentication no/' $SSHD_CONFIG
sed -i 's/^#\?PubkeyAuthentication.*/PubkeyAuthentication yes/' $SSHD_CONFIG
sed -i 's/^#\?X11Forwarding.*/X11Forwarding no/' $SSHD_CONFIG
sed -i 's/^#\?MaxAuthTries.*/MaxAuthTries 3/' $SSHD_CONFIG

# Validate SSH config before restarting
if sshd -t; then
  systemctl reload sshd
  echo -e "  ${GREEN}✓${NC} SSH hardened (root login disabled, password auth disabled)"
else
  echo -e "  ${RED}✗${NC} SSH config validation failed, restoring backup..."
  cp ${SSHD_CONFIG}.backup $SSHD_CONFIG
fi

# =============================================================================
# 5. System Updates
# =============================================================================
echo -e "${YELLOW}[5/5] Installing system updates...${NC}"

apt-get upgrade -y -qq
apt-get autoremove -y -qq
echo -e "  ${GREEN}✓${NC} System updated"

# =============================================================================
# Summary
# =============================================================================
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║          Setup Complete!                 ║${NC}"
echo -e "${GREEN}╚══════════════════════════════════════════╝${NC}"
echo ""
echo -e "Next steps:"
echo -e "  1. Update your local .env file:"
echo -e "     ${YELLOW}VPS_USER=deploy${NC}"
echo -e ""
echo -e "  2. Test SSH access with the new user:"
echo -e "     ${YELLOW}ssh deploy@<your-server-ip>${NC}"
echo -e ""
echo -e "  3. Deploy the application:"
echo -e "     ${YELLOW}cd /home/deploy/Aurora && docker compose -f docker-compose.prod.yml up -d${NC}"
echo ""
echo -e "${RED}⚠️  IMPORTANT: Test SSH access with 'deploy' user BEFORE logging out!${NC}"
echo -e "${RED}   Keep this root session open until you confirm 'deploy' user works.${NC}"
