#!/bin/bash

# --- Configuration ---
echo "This script will create a deployment script and a secure webhook listener for your Laravel project."
read -p "Enter the absolute path to your project's root directory (e.g., /var/www/my-app): " PROJECT_PATH

# Validate the project path
if [ -z "$PROJECT_PATH" ] || [ ! -d "$PROJECT_PATH" ] || [ ! -f "$PROJECT_PATH/artisan" ]; then
    echo "Error: Invalid path. Please provide the absolute path to a valid Laravel project directory."
    exit 1
fi

# --- Generation ---
echo "🚀 Generating secure credentials and scripts..."
# Generate a random, unique name for the PHP webhook file
WEBHOOK_FILENAME="hook-$(openssl rand -hex 16).php"
# Generate a strong secret key for webhook verification
SECRET_KEY=$(openssl rand -hex 20)
# Define a unique name for the deployment script
DEPLOY_SCRIPT_NAME="deploy-$(basename $PROJECT_PATH).sh"
# Define the path for the script inside the current user's home directory
DEPLOY_SCRIPT_PATH="$HOME/$DEPLOY_SCRIPT_NAME"


# --- Create Deployment Script ---
echo "Creating deployment script at $DEPLOY_SCRIPT_PATH..."
cat > "$DEPLOY_SCRIPT_PATH" << EOL
#!/bin/bash
# Deployment script for project at $PROJECT_PATH
# Executed by the web server user (e.g., www-data)

echo "--- Starting deployment for $PROJECT_PATH @ \$(date) ---"

# Navigate to the project directory
cd $PROJECT_PATH || { echo "Error: Could not navigate to project directory."; exit 1; }

# Pull the latest changes from the 'production' branch
# Ensure the web server user has SSH deploy key access to the repo
git pull origin production

# Install/update composer dependencies using the full path to PHP if necessary
# Use --no-dev for production environments
composer install --no-interaction --no-dev --prefer-dist --optimize-autoloader

# Run database migrations without interaction
php artisan migrate --force

# Clear and cache configurations for performance
php artisan optimize

# Optional: Build frontend assets if your project uses them
# if [ -f "package.json" ]; then
#   npm install
#   npm run build
# fi

echo "--- Deployment finished successfully ---"
EOL

# Make the deployment script executable
chmod 755 "$DEPLOY_SCRIPT_PATH"


# --- Create PHP Webhook Listener ---
echo "Creating PHP webhook listener..."
PHP_FILE_PATH="$PROJECT_PATH/public/$WEBHOOK_FILENAME"

cat > "$PHP_FILE_PATH" << EOL
<?php
// --- Secure, Autogenerated Webhook Listener ---

\$secret = '${SECRET_KEY}';
\$deployScript = '${DEPLOY_SCRIPT_PATH}'; // This path is now correctly set to the user's home directory
\$logFile = __DIR__ . '/../storage/logs/webhook.log';

// 1. Verify the request is a POST request
if (\$_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    exit('Method Not Allowed');
}

// 2. Verify the signature from GitHub to ensure authenticity
\$signature = \$_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';
if (!\$signature) {
    http_response_code(403);
    exit('Signature not found.');
}

\$payload = file_get_contents('php://input');
\$hash = 'sha256=' . hash_hmac('sha256', \$payload, \$secret);

if (!hash_equals(\$hash, \$signature)) {
    http_response_code(403);
    exit('Invalid signature.');
}

// 3. Execute the deployment script
\$output = shell_exec('bash ' . escapeshellarg(\$deployScript) . ' 2>&1');

// 4. Log the output for debugging
\$logMessage = "[" . date('Y-m-d H:i:s') . "] --- Deployment Triggered ---\\n" . \$output . "\\n";
file_put_contents(\$logFile, \$logMessage, FILE_APPEND);

echo "Webhook processed successfully.";
?>
EOL


# --- Final Output ---
echo ""
echo "✅ Setup Complete!"
echo "----------------------------------------------------------------"
echo "Go to your GitHub repo > Settings > Webhooks > Add webhook"
echo "and paste the following details:"
echo ""
echo "➡️  Payload URL:"
echo "   (Remember to replace 'your-domain.com' with your actual domain)"
echo "   https://your-domain.com/$WEBHOOK_FILENAME"
echo ""
echo "➡️  Secret:"
echo "   $SECRET_KEY"
echo ""
echo "➡️  Content type: application/json"
echo "----------------------------------------------------------------"
echo "Next Steps & Reminders:"
echo "1. Ensure your web server owns Laravel's storage folder: sudo chown -R www-data:www-data $PROJECT_PATH/storage"
echo "2. Make sure you've added an SSH deploy key to your repo for the www-data user."
