# Deployment Setup Guide

This document covers the setup required to deploy the staging environment to a DigitalOcean droplet via GitHub Actions.

## GitHub Secrets

Configure the following secrets in your GitHub repository settings (**Settings > Secrets and variables > Actions**):

| Secret Name | Description | Example |
|---|---|---|
| `DEPLOY_SSH_HOST` | IP address or hostname of the DigitalOcean droplet | `192.0.2.1` or `staging.example.com` |
| `DEPLOY_SSH_USER` | Username of the dedicated deploy user | `deploy` |
| `DEPLOY_SSH_KEY` | Private SSH key (multi-line) | (see below for generation) |
| `DEPLOY_SSH_PORT` | SSH port (optional, defaults to 22) | `2222` |

### Generating the Deploy SSH Key Pair

On your local machine:

```bash
ssh-keygen -t ed25519 -C "github-deploy@mulholland" -f deploy_key -N ""
# This creates:
#   deploy_key (private key) — store this as DEPLOY_SSH_KEY secret
#   deploy_key.pub (public key) — add this to server's authorized_keys
```

Copy the **private key** contents (including newlines) into the `DEPLOY_SSH_KEY` secret.

## Server Prerequisites

These steps must be completed **once** on the DigitalOcean droplet before the first deploy.

### 1. System Dependencies

Ensure the following are installed on the droplet (Ubuntu 24.04):

- **Apache 2.4** with `mod_proxy` and `mod_proxy_fcgi` enabled
- **PHP 8.3-FPM** (not `mod_php`)
  ```bash
  sudo apt update
  sudo apt install -y apache2 php8.3-fpm php8.3-cli php8.3-curl php8.3-gd php8.3-mbstring php8.3-mysqli php8.3-xml
  sudo a2enmod proxy proxy_fcgi
  sudo systemctl restart apache2
  ```
- **MySQL 8.0+** (local or managed)
- **Composer** (globally)
  ```bash
  curl -sS https://getcomposer.org/installer | php
  sudo mv composer.phar /usr/local/bin/composer
  ```
- **Node.js 20+** and **npm 10+**
  ```bash
  curl -sL https://deb.nodesource.com/setup_20.x | sudo bash
  sudo apt install -y nodejs
  ```

### 2. Create the Deploy User

```bash
sudo useradd -m -s /bin/bash deploy
sudo mkdir -p /home/deploy/.ssh
sudo chmod 700 /home/deploy/.ssh
```

Add the public key from step above to the authorized_keys:

```bash
echo "ssh-ed25519 AAAA..." | sudo tee -a /home/deploy/.ssh/authorized_keys
sudo chmod 600 /home/deploy/.ssh/authorized_keys
sudo chown -R deploy:deploy /home/deploy/.ssh
```

### 3. Configure Passwordless Sudo (for PHP-FPM reload)

Allow the `deploy` user to reload PHP-FPM without a password prompt:

```bash
sudo tee /etc/sudoers.d/deploy-php-fpm > /dev/null << 'EOF'
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl reload php8.3-fpm
EOF
sudo chmod 440 /etc/sudoers.d/deploy-php-fpm
```

Test it (should not prompt for password):
```bash
sudo -u deploy sudo systemctl reload php8.3-fpm
```

### 4. Set Up the Web Root

Create the deployment directory and ensure the deploy user owns it:

```bash
sudo mkdir -p /var/www/html
sudo chown -R deploy:deploy /var/www/html
sudo chmod -R 755 /var/www/html
```

Clone the repository as the deploy user. First, the repository must be accessible via SSH from the droplet. Options:

**Option A: Use the same GitHub deploy key** (simplest for this use case)

```bash
sudo -u deploy ssh-keygen -t ed25519 -C "deploy@mulholland-staging" -f /home/deploy/.ssh/github_deploy -N ""
# Add the public key (deploy_key.pub output) to GitHub repo deploy keys
# Then configure SSH to use this key for GitHub:
sudo -u deploy tee /home/deploy/.ssh/config > /dev/null << 'EOF'
Host github.com
    User git
    IdentityFile ~/.ssh/github_deploy
    IdentitiesOnly yes
EOF
sudo -u deploy chmod 600 /home/deploy/.ssh/config
```

**Option B: Use HTTPS with a personal access token** (if you prefer)

Store a GitHub personal access token and use it in the clone URL:

```bash
sudo -u deploy git config --global credential.helper store
# Then first clone will prompt for token, which gets stored
```

Clone the repo into `/var/www/html`:

```bash
sudo -u deploy git clone git@github.com:Pragmatic-Digital/mulholland.git /var/www/html
cd /var/www/html
sudo -u deploy git checkout staging
```

### 5. Install Dependencies (First Time)

```bash
cd /var/www/html
sudo -u deploy composer install --no-dev --optimize-autoloader --no-interaction
cd web/app/plugins/timeline-player
sudo -u deploy npm ci
sudo -u deploy npm run build
```

### 6. Configure Apache Virtual Host

Create a vhost config for `staging.<domain>` (replace `staging.example.com` with your actual subdomain):

```bash
sudo tee /etc/apache2/sites-available/staging-mulholland.conf > /dev/null << 'EOF'
<VirtualHost *:80>
    ServerName staging.example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/html/web

    <Directory /var/www/html/web>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
        
        <IfModule mod_rewrite.c>
            RewriteEngine On
            RewriteCond %{REQUEST_FILENAME} !-f
            RewriteCond %{REQUEST_FILENAME} !-d
            RewriteRule ^ /index.php [L]
        </IfModule>
    </Directory>

    <IfModule mod_proxy_fcgi.c>
        <FilesMatch "\.php$">
            SetHandler "proxy:unix:/run/php/php8.3-fpm.sock|fcgi://localhost"
        </FilesMatch>
    </IfModule>

    ErrorLog ${APACHE_LOG_DIR}/staging-error.log
    CustomLog ${APACHE_LOG_DIR}/staging-access.log combined
</VirtualHost>
EOF

sudo a2ensite staging-mulholland.conf
sudo apache2ctl configtest  # Should output "Syntax OK"
sudo systemctl reload apache2
```

### 7. Set Up HTTPS with Certbot

```bash
sudo apt install -y certbot python3-certbot-apache
sudo certbot --apache -d staging.example.com
```

Follow the prompts. This will automatically configure SSL and enable auto-renewal.

### 8. Create the `.env` File

On the server, create `/var/www/html/.env` with your environment variables. This file is **never** modified by the GitHub Action — you maintain it manually on the server:

```bash
cat > /var/www/html/.env << 'EOF'
DB_NAME='mulholland_staging'
DB_USER='wordpress'
DB_PASSWORD='<secure-password>'
DB_HOST='localhost'

WP_ENV='staging'
WP_HOME='https://staging.example.com'
WP_SITEURL="${WP_HOME}/wp"

AUTH_KEY='<random-key-1>'
SECURE_AUTH_KEY='<random-key-2>'
LOGGED_IN_KEY='<random-key-3>'
NONCE_KEY='<random-key-4>'
AUTH_SALT='<random-salt-1>'
SECURE_AUTH_SALT='<random-salt-2>'
LOGGED_IN_SALT='<random-salt-3>'
NONCE_SALT='<random-salt-4>'
EOF

sudo chown deploy:deploy /var/www/html/.env
sudo chmod 600 /var/www/html/.env
```

Generate secure keys/salts with:
```bash
# Generate random strings for each key/salt (copy 64-char strings)
openssl rand -base64 32
```

Or use the [WordPress Salt Generator](https://api.wordpress.org/secret-key/1.1/salt/).

## Deployment Workflow

Once the server is set up, deployments happen automatically:

1. **Push to `staging` branch**
   ```bash
   git push origin staging
   ```

2. **GitHub Actions workflow triggers automatically**
   - Logs in to the droplet via SSH
   - Runs `git fetch origin staging && git reset --hard origin/staging`
   - Installs Composer dependencies: `composer install --no-dev --optimize-autoloader --no-interaction`
   - Builds the timeline-player plugin: `cd web/app/plugins/timeline-player && npm ci && npm run build`
   - Reloads PHP-FPM: `sudo systemctl reload php8.3-fpm`

3. **Monitor the workflow**
   - View status in **GitHub Actions** tab
   - Check server logs if needed:
     ```bash
     tail -f /var/log/apache2/staging-error.log
     sudo journalctl -u php8.3-fpm -n 50
     ```

## Manual Verification

After a deploy, verify it succeeded:

```bash
# SSH into the droplet
ssh deploy@<droplet-ip>

# Check the latest deployed commit
cd /var/www/html && git log -1

# Verify builds are up-to-date
ls -la web/app/plugins/timeline-player/build/
ls -la vendor/

# Check PHP-FPM status
sudo systemctl status php8.3-fpm

# Visit the site
# https://staging.example.com should load successfully
```

## Troubleshooting

### Workflow fails with "Permission denied (publickey)"
- Verify the deploy user's `authorized_keys` has the correct public key from `DEPLOY_SSH_KEY`
- Check SSH connectivity: `ssh -i <private-key> deploy@<host> echo "Success"`

### Composer/npm step fails
- SSH into the server and run the command manually to see detailed error
- Ensure Composer and Node.js are installed and in the PATH
- Check file permissions: `ls -la /var/www/html` should show `deploy` as owner

### PHP-FPM reload fails
- Verify the sudoers entry: `sudo -u deploy sudo -l` should show the reload command allowed
- Check PHP-FPM status: `sudo systemctl status php8.3-fpm`

### Site returns 502 Bad Gateway
- Check if PHP-FPM is running: `sudo systemctl status php8.3-fpm`
- Check Apache error log: `tail -f /var/log/apache2/staging-error.log`
- Verify the socket path in the vhost config matches the PHP-FPM config (typically `/run/php/php8.3-fpm.sock`)

### Database connection errors
- Verify `.env` has correct `DB_*` variables
- Confirm MySQL is running and accessible from localhost
- Check database exists: `mysql -u wordpress -p -h localhost -e "USE mulholland_staging; SELECT 1;"`

## Database Initialization (First Time Only)

If starting from scratch, you'll need to initialize the WordPress database. One of:

1. **Use the WordPress installation UI** (if accessible)
2. **Import a database dump** (if you have a backup)
   ```bash
   mysql -u wordpress -p mulholland_staging < /path/to/dump.sql
   ```
3. **Use WP-CLI** (if installed)
   ```bash
   cd /var/www/html
   wp core install --url="https://staging.example.com" --title="Mulholland Staging" --admin_user="admin" --admin_email="admin@example.com" --admin_password="<secure-password>"
   ```
