#!/bin/bash
# Generate secure passwords and WordPress salts for .env.prod
# Usage: ./generate-env-secrets.sh [project-name] [domain]
# Example: ./generate-env-secrets.sh php-wp-ch_hair_select hair-sct.ch

set -e

PROJECT_NAME="${1:-php-wp-example}"
DOMAIN="${2:-example.com}"
TABLE_PREFIX="${3:-wp_}"

# Generate random passwords
DB_ROOT_PASSWORD=$(openssl rand -base64 32)
DB_PASSWORD=$(openssl rand -base64 32)
FTP_PASSWORD=$(openssl rand -base64 24)

# Fetch WordPress salts from official API
echo "Fetching WordPress salts from api.wordpress.org..."
SALTS=$(curl -s https://api.wordpress.org/secret-key/1.1/salt/)

# Extract individual salt values and escape for shell
extract_salt() {
    echo "$SALTS" | grep "define('$1'" | sed "s/define('$1', *'//" | sed "s/');$//" | sed "s/\\\$/\\\\\$/g" | sed "s/\`/\\\\\`/g"
}

AUTH_KEY=$(extract_salt "AUTH_KEY")
SECURE_AUTH_KEY=$(extract_salt "SECURE_AUTH_KEY")
LOGGED_IN_KEY=$(extract_salt "LOGGED_IN_KEY")
NONCE_KEY=$(extract_salt "NONCE_KEY")
AUTH_SALT=$(extract_salt "AUTH_SALT")
SECURE_AUTH_SALT=$(extract_salt "SECURE_AUTH_SALT")
LOGGED_IN_SALT=$(extract_salt "LOGGED_IN_SALT")
NONCE_SALT=$(extract_salt "NONCE_SALT")

# Write .env.prod
cat > .env.prod << EOF
REVERSE_DOMAIN=${PROJECT_NAME}
DB_ROOT_PASSWORD=${DB_ROOT_PASSWORD}
DB_NAME=${PROJECT_NAME}-db_name
DB_USER=${PROJECT_NAME}-db_user
DB_PASSWORD=${DB_PASSWORD}
APPLICATION_DOMAIN_NAME=${DOMAIN}
DOCKER_IMAGE=wordpress
DOCKER_IMAGE_TAG=latest
AUTH_KEY="'${AUTH_KEY}'"
SECURE_AUTH_KEY="'${SECURE_AUTH_KEY}'"
LOGGED_IN_KEY="'${LOGGED_IN_KEY}'"
NONCE_KEY="'${NONCE_KEY}'"
AUTH_SALT="'${AUTH_SALT}'"
SECURE_AUTH_SALT="'${SECURE_AUTH_SALT}'"
LOGGED_IN_SALT="'${LOGGED_IN_SALT}'"
NONCE_SALT="'${NONCE_SALT}'"
TABLE_PREFIX=${TABLE_PREFIX}

WP_DEBUG=1
WP_DEBUG_LOG=1
WP_DEBUG_DISPLAY=false
DISABLE_WP_CRON=true

FTP_USERNAME=admin
FTP_PASSWORD=${FTP_PASSWORD}
EOF

echo "Generated .env.prod for ${PROJECT_NAME} (${DOMAIN})"
echo "Remember to update TABLE_PREFIX if migrating existing database!"
