#!/bin/bash
# Deploy rethinkaadhaar.in to VPS
# Prerequisites: PHP 8.x + php-fpm + php-sqlite3 + php-xml + php-mbstring + php-curl + php-gd + nginx
# Run as root on VPS: ./deploy.sh

set -e

WP_DIR="/var/www/rethinkaadhaar"
DOMAIN="rethinkaadhaar.in"

echo "Installing WordPress to ${WP_DIR}..."

# Copy files
mkdir -p "$WP_DIR"
cp -a wordpress/ "$WP_DIR/"
chown -R www-data:www-data "$WP_DIR"
chmod -R 755 "$WP_DIR"

# Generate salts
SALTS=$(curl -fsSL https://api.wordpress.org/secret-key/1.1/salt/)

# Create production wp-config.php with real salts
cat > "$WP_DIR/wp-config.php" << PHPEOF
<?php
define('DB_NAME', 'rethinkaadhaar');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8mb4');

\$table_prefix = 'wp_';
define('WP_DEBUG', false);
define('DB_ENGINE', 'sqlite');
define('WP_HOME', 'https://${DOMAIN}');
define('WP_SITEURL', 'https://${DOMAIN}');

${SALTS}

if (!defined('ABSPATH')) define('ABSPATH', __DIR__ . '/');
require_once ABSPATH . 'wp-settings.php';
PHPEOF

# Nginx config
cat > /etc/nginx/sites-available/rethinkaadhaar << 'NGEOF'
server {
    listen 80;
    server_name ${DOMAIN} www.${DOMAIN};
    root ${WP_DIR};
    index index.php index.html;
    client_max_body_size 64M;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_intercept_errors on;
    }
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires max; log_not_found off;
    }
    location ~ /\.ht { deny all; }
}
NGEOF

ln -sf /etc/nginx/sites-available/rethinkaadhaar /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

echo "Deployed! Visit https://${DOMAIN}/wp-admin to configure SSL and finalize."
echo "Admin login: check your existing admin user or run:"
echo "  php ${WP_DIR}/wp-cli.phar user list"
