#!/bin/bash

set -e

# Trap CTRL+C
trap 'echo -e "\033[1;31m\n[!] Exiting...\033[0m"; exit 1' INT

# Base dir
BASE_DIR="/opt/convesio_$(date +%s)"
mkdir -p "$BASE_DIR/config"

# Generate secure random passwords
generate_password() {
    tr -dc 'A-Za-z0-9' </dev/urandom | head -c 16
}

WORDPRESS_DB_PASSWORD=$(generate_password)
MYSQL_ROOT_PASSWORD=$(generate_password)

# Pick a free random port
PORT=$(comm -23 <(seq 8000 9000 | sort) <(cat /proc/net/tcp /proc/net/udp | awk '{print $2}' | cut -d: -f2 | sort -u) | shuf | head -n 1)

# Pull latest images
docker pull wordpress:6.6.2-fpm-alpine
docker pull mariadb:10.11
docker pull redis:7.2-alpine
docker pull nginx:1.25-alpine

# Create a private network
docker network create convesio_network_$(basename "$BASE_DIR")

# Launch MariaDB
docker run -d \
  --name convesio_db_$(basename "$BASE_DIR") \
  --network convesio_network_$(basename "$BASE_DIR") \
  -e MYSQL_ROOT_PASSWORD="$MYSQL_ROOT_PASSWORD" \
  -e MYSQL_DATABASE=wordpress \
  -e MYSQL_USER=wordpress \
  -e MYSQL_PASSWORD="$WORDPRESS_DB_PASSWORD" \
  -v "$BASE_DIR/mysql_data:/var/lib/mysql" \
  --restart unless-stopped \
  mariadb:10.11

# Launch Redis
docker run -d \
  --name convesio_redis_$(basename "$BASE_DIR") \
  --network convesio_network_$(basename "$BASE_DIR") \
  --restart unless-stopped \
  redis:7.2-alpine

# Create uploads.ini for PHP configuration
mkdir -p "$BASE_DIR/config/php"
cat << EOF > "$BASE_DIR/config/php/uploads.ini"
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
memory_limit = 256M
display_errors = On
error_reporting = E_ALL
EOF

# Launch WordPress
docker run -d \
  --name convesio_wordpress_$(basename "$BASE_DIR") \
  --network convesio_network_$(basename "$BASE_DIR") \
  -e WORDPRESS_DB_HOST=convesio_db_$(basename "$BASE_DIR") \
  -e WORDPRESS_DB_USER=wordpress \
  -e WORDPRESS_DB_PASSWORD="$WORDPRESS_DB_PASSWORD" \
  -e WORDPRESS_DB_NAME=wordpress \
  -v "$BASE_DIR/wordpress_data:/var/www/html" \
  -v "$BASE_DIR/config/php/uploads.ini:/usr/local/etc/php/conf.d/uploads.ini" \
  --restart unless-stopped \
  wordpress:6.6.2-fpm-alpine

# Nginx config with increased timeouts
mkdir -p "$BASE_DIR/config"
cat << EOF > "$BASE_DIR/config/default.conf"
server {
    listen 80;
    server_name localhost;
    root /var/www/html;
    index index.php index.html index.htm;

    # Allow larger upload sizes and larger request headers
    client_max_body_size 64M;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;  # Increase buffer size if necessary
    proxy_buffers 8 16k;
    proxy_buffer_size 16k;
    fastcgi_buffers 16 16k;
    fastcgi_buffer_size 32k;
    
    server_tokens off;

    client_body_timeout 60s;
    client_header_timeout 60s;
    keepalive_timeout 60s;
    fastcgi_read_timeout 300s;
    send_timeout 60s;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_vary on;

    location / {
        try_files \$uri \$uri/ /index.php?\$args;
    }

    location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|svg|ttf|otf|eot|mp4)$ {
        expires 30d;
        access_log off;
        add_header Cache-Control "public, max-age=2592000, immutable";
    }

    location ~ \.php\$ {
        include fastcgi_params;
        fastcgi_pass convesio_wordpress_$(basename "$BASE_DIR"):9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;

        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
    }
}
EOF

# Launch Nginx with increased timeouts
docker run -d \
  --name convesio_nginx_$(basename "$BASE_DIR") \
  --network convesio_network_$(basename "$BASE_DIR") \
  -p "$PORT:80" \
  -v "$BASE_DIR/wordpress_data:/var/www/html" \
  -v "$BASE_DIR/config/default.conf:/etc/nginx/conf.d/default.conf" \
  --restart unless-stopped \
  nginx:1.25-alpine

# Save a cleanup script
cat << EOF > "$BASE_DIR/cleanup.sh"
#!/bin/bash
docker rm -f convesio_nginx_$(basename "$BASE_DIR") convesio_wordpress_$(basename "$BASE_DIR") convesio_db_$(basename "$BASE_DIR") convesio_redis_$(basename "$BASE_DIR")
docker network rm convesio_network_$(basename "$BASE_DIR")
rm -rf "$BASE_DIR"
EOF

chmod +x "$BASE_DIR/cleanup.sh"

# Final Output
echo -e "\033[1;32m[SUCCESS]\033[0m WordPress is running at: http://localhost:$PORT"
echo -e "\033[1;34m[*]\033[0m WordPress DB User: wordpress"
echo -e "\033[1;34m[*]\033[0m WordPress DB Password: $WORDPRESS_DB_PASSWORD"
echo -e "\033[1;34m[*]\033[0m MySQL Root Password: $MYSQL_ROOT_PASSWORD"
echo -e "\033[1;34m[*]\033[0m Files located at: $BASE_DIR"

echo -e "\n\033[1;31m[!] To STOP and DELETE everything, run:\033[0m"
echo -e "\033[1;31msh $BASE_DIR/cleanup.sh\033[0m"