#cloud-config
autoinstall:
  # version is an Autoinstall required field.
  version: 1

  # Install Ubuntu server packages and ThrillWiki dependencies
  packages:
    - ubuntu-server
    - curl
    - wget
    - git
    - python3
    - python3-pip
    - python3-venv
    - nginx
    - postgresql
    - postgresql-contrib
    - redis-server
    - nodejs
    - npm
    - build-essential
    - ufw
    - fail2ban
    - htop
    - tree
    - vim
    - tmux
    - qemu-guest-agent

  # User creation
  identity:
    realname: 'ThrillWiki Admin'
    username: thrillwiki
    # Default [PASSWORD-REMOVED] (change after login)
    password: '$6$rounds=4096$saltsalt$[AWS-SECRET-REMOVED]AzpI8g8T14F8VnhXo0sUkZV2NV6/.c77tHgVi34DgbPu.'
    hostname: thrillwiki-vm

  locale: en_US.UTF-8
  keyboard:
    layout: us

  package_update: true
  package_upgrade: true

  # Use direct storage layout (no LVM)
  storage:
    swap:
      size: 0
    layout:
      name: direct

  # SSH configuration
  ssh:
    allow-pw: true
    install-server: true
    authorized-keys:
      - {SSH_PUBLIC_KEY}

  # Network configuration - will be replaced with proper config
  network:
    version: 2
    ethernets:
      enp1s0:
        dhcp4: true
        dhcp-identifier: mac

  # Commands to run after installation
  late-commands:
    # Update GRUB
    - curtin in-target -- update-grub
    
    # Enable and start services
    - curtin in-target -- systemctl enable qemu-guest-agent
    - curtin in-target -- systemctl enable postgresql
    - curtin in-target -- systemctl enable redis-server
    - curtin in-target -- systemctl enable nginx
    
    # Configure PostgreSQL
    - curtin in-target -- sudo -u postgres createuser -s thrillwiki
    - curtin in-target -- sudo -u postgres createdb thrillwiki_db
    - curtin in-target -- sudo -u postgres psql -c "ALTER USER thrillwiki PASSWORD 'thrillwiki123';"
    
    # Configure firewall
    - curtin in-target -- ufw allow OpenSSH
    - curtin in-target -- ufw allow 'Nginx Full'
    - curtin in-target -- ufw --force enable
    
    # Clone ThrillWiki repository if provided
    - curtin in-target -- bash -c 'if [ -n "{GITHUB_REPO}" ]; then cd /home/thrillwiki && git clone "{GITHUB_REPO}" thrillwiki-app && chown -R thrillwiki:thrillwiki thrillwiki-app; fi'
    
    # Create deployment script
    - curtin in-target -- tee /home/thrillwiki/deploy-thrillwiki.sh << 'EOF'
#!/bin/bash
set -e

echo "=== ThrillWiki Deployment Script ==="

# Check if repo was cloned
if [ ! -d "/home/thrillwiki/thrillwiki-app" ]; then
    echo "Repository not found. Please clone your ThrillWiki repository:"
    echo "git clone YOUR_REPO_URL thrillwiki-app"
    exit 1
fi

cd /home/thrillwiki/thrillwiki-app

# Create virtual environment
python3 -m venv venv
source venv/bin/activate

# Install Python dependencies
if [ -f "requirements.txt" ]; then
    pip install -r requirements.txt
else
    echo "Warning: requirements.txt not found"
fi

# Install Django if not in requirements
pip install django psycopg2-binary redis celery gunicorn

# Set up environment variables
cat > ***REMOVED*** << 'ENVEOF'
DEBUG=False
SECRET_KEY=your-secret-key-change-this
DATABASE_URL=[DATABASE-URL-REMOVED]
REDIS_URL=redis://localhost:6379/0
ALLOWED_HOSTS=localhost,127.0.0.1,thrillwiki-vm
ENVEOF

# Run Django setup commands
if [ -f "manage.py" ]; then
    python manage.py collectstatic --noinput
    python manage.py migrate
    echo "from django.contrib.auth import get_user_model; User = get_user_model(); User.objects.create_superuser('admin', 'admin@thrillwiki.com', 'thrillwiki123') if not User.objects.filter(username='admin').exists() else None" | python manage.py shell
fi

# Configure Nginx
sudo tee /etc/nginx/sites-available/thrillwiki << 'NGINXEOF'
server {
    listen 80;
    server_name _;
    
    location /static/ {
        alias /home/thrillwiki/thrillwiki-app/staticfiles/;
    }
    
    location /media/ {
        alias /home/thrillwiki/thrillwiki-app/media/;
    }
    
    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }
}
NGINXEOF

# Enable Nginx site
sudo ln -sf /etc/nginx/sites-available/thrillwiki /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo systemctl reload nginx

# Create systemd service for Django
sudo tee /etc/systemd/system/thrillwiki.service << 'SERVICEEOF'
[Unit]
Description=ThrillWiki Django App
After=network.target

[Service]
User=thrillwiki
Group=thrillwiki
[AWS-SECRET-REMOVED]wiki-app
[AWS-SECRET-REMOVED]wiki-app/venv/bin
ExecStart=/home/thrillwiki/thrillwiki-app/venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8000 thrillwiki.wsgi:application
Restart=always

[Install]
WantedBy=multi-user.target
SERVICEEOF

# Enable and start ThrillWiki service
sudo systemctl daemon-reload
sudo systemctl enable thrillwiki
sudo systemctl start thrillwiki

echo "=== ThrillWiki deployment complete! ==="
echo "Access your application at: http://$(hostname -I | awk '{print $1}')"
echo "Django Admin: http://$(hostname -I | awk '{print $1}')/admin"
echo "Default superuser: admin / thrillwiki123"
echo ""
echo "Important: Change default passwords!"
EOF
    
    # Make deployment script executable
    - curtin in-target -- chmod +x /home/thrillwiki/deploy-thrillwiki.sh
    - curtin in-target -- chown thrillwiki:thrillwiki /home/thrillwiki/deploy-thrillwiki.sh
    
    # Clean up
    - curtin in-target -- apt-get autoremove -y
    - curtin in-target -- apt-get autoclean

  # Reboot after installation
  shutdown: reboot
