#!/bin/bash
# Networksolutions.com VPS Setup Script
# Run this on your fresh VPS after initial SSH access

set -e

echo "========================================"
echo "Networksolutions.com VPS Automation Setup"
echo "========================================"
echo ""

# Configuration
PROJECT_NAME="StartupLX"
DOMAIN="kenprogroup.com"
WEB_ROOT="/var/www/${PROJECT_NAME,,}"
N8N_PASSWORD=$(openssl rand -base64 32)

# Step 1: Create non-root user
echo "[1/8] Creating non-root user..."
adduser -D ryleostealth
echo "ryleostealth:ryleostealth" | chpasswd
usermod -aG sudo ryleostealth

# Step 2: Install essential packages
echo "[2/8] Installing essential packages..."
apt-get update
apt-get install -y \
    curl \
    wget \
    git \
    ufw \
    fail2ban \
    nginx \
    certbot \
    python3-certbot-nginx \
    sqlite3

# Step 3: Configure firewall
echo "[3/8] Configuring firewall..."
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

# Step 4: Install Docker
echo "[4/8] Installing Docker..."
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
apt-get install -y docker-compose
systemctl start docker
systemctl enable docker

# Step 5: Create project structure
echo "[5/8] Creating project structure..."
mkdir -p ${WEB_ROOT}/{website,automation,logs,ssl,n8n-data,nginx}
chown -R ryleostealth:ryleostealth ${WEB_ROOT}

# Step 6: Create docker-compose.yml
echo "[6/8] Creating Docker Compose configuration..."
cat > ${WEB_ROOT}/docker-compose.yml << 'DOCKERFILE'
version: '3.8'

services:
  n8n:
    image: n8nio/n8n:latest
    restart: unless-stopped
    ports:
      - "3000:5678"
    environment:
      - N8N_BASIC_AUTH_ACTIVE=true
      - N8N_BASIC_AUTH_USER=${N8N_USER}
      - N8N_BASIC_AUTH_PASSWORD=${N8N_PASSWORD}
      - N8N_HOST=localhost
      - N8N_PORT=5678
      - N8N_PROTOCOL=http
      - DB_TYPE=sqlite
      - DB_SQLITE_VACUUM_ON_STARTUP=true
    volumes:
      - ./n8n-data:/home/node/.n8n
    networks:
      - startuplx-network

  metabase:
    image: metabase/metabase:v0.47.6
    restart: unless-stopped
    ports:
      - "3001:3000"
    volumes:
      - ./metabase-data:/metabase-data
    networks:
      - startuplx-network

  nginx:
    image: nginx:alpine
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf
      - ./ssl:/etc/nginx/ssl
      - ./website/public:/usr/share/nginx/html
    depends_on:
      - n8n
    networks:
      - startuplx-network

networks:
  startuplx-network:
    driver: bridge
DOCKERFILE

# Step 7: Create nginx configuration
echo "[7/8] Creating Nginx configuration..."
cat > ${WEB_ROOT}/nginx/nginx.conf << 'NGINXCONF'
events {
    worker_connections 1024;
}

http {
    upstream n8n {
        server n8n:5678;
    }

    server {
        listen 80;
        server_name _;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        server_name _;
        
        ssl_certificate /etc/nginx/ssl/fullchain.pem;
        ssl_certificate_key /etc/nginx/ssl/privkey.pem;
        
        location / {
            proxy_pass http://n8n;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
        
        location /website/ {
            alias /usr/share/nginx/html/;
            try_files $uri $uri/ =404;
        }
        
        location /health {
            return 200 'OK';
            add_header Content-Type text/plain;
        }
    }
}
NGINXCONF

# Step 8: Create .env file with secure password
echo "[8/8] Creating environment file..."
cat > ${WEB_ROOT}/.env << EOF
N8N_USER=ryleostealth
N8N_PASSWORD=${N8N_PASSWORD}
EOF

# Set ownership
chown ryleostealth:ryleostealth ${WEB_ROOT}/.env

# Create simple health check script
cat > ${WEB_ROOT}/scripts/health-check.sh << 'HEALTHSCRIPT'
#!/bin/bash
echo "=== $(date) ==="
echo "Docker Containers:"
docker-compose ps
echo ""
echo "Disk Usage:"
df -h /var/www/
HEALTHSCRIPT
chmod +x ${WEB_ROOT}/scripts/health-check.sh
chown ryleostealth:ryleostealth ${WEB_ROOT}/scripts/health-check.sh

echo ""
echo "========================================"
echo "✅ Setup Complete!"
echo "========================================"
echo ""
echo "Next Steps:"
echo "1. SSH into VPS as ryleostealth: ssh ryleostealth@YOUR_VPS_IP"
echo "2. Navigate to project: cd ${WEB_ROOT}"
echo "3. Add SSL certificates: certbot --nginx -d ${DOMAIN}"
echo "4. Start services: docker-compose up -d"
echo "5. Access n8n: https://${DOMAIN}:3000"
echo "6. Access Metabase: https://${DOMAIN}:3001"
echo ""
echo "Saved n8n password: ${N8N_PASSWORD}"
echo "SAVE THIS PASSWORD IMMEDIATELY!"
echo ""