cat > add-wordpress-site-v6.sh << 'MAINSCRIPT'
#!/bin/sh

cat << 'EOF'
==========================================
Add WordPress Site to Existing Deployment
v6 - Ansible-based (matches v4 style)
==========================================

REQUIREMENTS:
- Existing Bastille WordPress deployment (v4+)
- db0, redis0, proxy0 jails already running

This script will:
1. Create a new web jail for the site
2. Install WordPress with nginx + PHP-FPM
3. Configure database and user
4. Install and enable Redis Object Cache
5. Set up pretty permalinks
6. Update proxy configuration
7. Optionally set up SSL certificate

CLEANUP (if script fails mid-way):
  bastille destroy -fay <jail_name>
  bastille cmd db0 mysql -u root -e "DROP USER IF EXISTS '<user>'@'<ip>';"
  bastille cmd db0 mysql -u root -e "DROP DATABASE IF EXISTS <db>;"

==========================================
EOF

read -p "Press Enter to continue or Ctrl+C to cancel... " dummy

# ==========================================
# VERIFY EXISTING INFRASTRUCTURE
# ==========================================

echo ""
echo "=========================================="
echo "STEP 1: Verifying existing infrastructure"
echo "=========================================="

# Check for required jails using jls
MISSING_JAILS=""
for JAIL in db0 redis0 proxy0; do
    if ! jls name | grep -q "^${JAIL}$"; then
        MISSING_JAILS="${MISSING_JAILS} ${JAIL}"
    fi
done

if [ -n "${MISSING_JAILS}" ]; then
    echo "ERROR: Missing required jails:${MISSING_JAILS}"
    echo "Please run the main deployment script first."
    exit 1
fi

echo "✓ All required jails found (db0, redis0, proxy0)"

# Get existing configuration using jls
DB_JAIL_IP=$(jls -j db0 ip4.addr | tr -d ' ')
REDIS_JAIL_IP=$(jls -j redis0 ip4.addr | tr -d ' ')
PROXY_JAIL_IP=$(jls -j proxy0 ip4.addr | tr -d ' ')

echo "  Database jail IP: ${DB_JAIL_IP}"
echo "  Redis jail IP: ${REDIS_JAIL_IP}"
echo "  Proxy jail IP: ${PROXY_JAIL_IP}"

# Count existing web jails to determine next Redis database number
EXISTING_SITES=$(jls name | grep -v -E "^db0$|^redis0$|^proxy0$" | wc -l | tr -d ' ')
NEXT_REDIS_DB=${EXISTING_SITES}
echo "  Existing web jails: ${EXISTING_SITES}"
echo "  Next Redis database: ${NEXT_REDIS_DB}"

# ==========================================
# INTERACTIVE CONFIGURATION
# ==========================================

echo ""
echo "=========================================="
echo "STEP 2: New Site Configuration"
echo "=========================================="

# Jail type
read -p "Use thick jail? (Y/n) [default: Y]: " JAIL_TYPE_INPUT
JAIL_TYPE_INPUT=${JAIL_TYPE_INPUT:-Y}
if [ "$JAIL_TYPE_INPUT" = "Y" ] || [ "$JAIL_TYPE_INPUT" = "y" ]; then
    JAIL_TYPE_FLAG="-T"
    JAIL_TYPE_NAME="thick"
else
    JAIL_TYPE_FLAG=""
    JAIL_TYPE_NAME="thin"
fi
echo "Using ${JAIL_TYPE_NAME} jail"

# Jail name
while true; do
    read -p "New site jail name (e.g., site3, myblog): " SITE_JAIL
    if [ -z "$SITE_JAIL" ]; then
        echo "Jail name cannot be empty"
    elif echo "$SITE_JAIL" | grep -qE '^[a-zA-Z0-9_-]+$'; then
        if jls name | grep -q "^${SITE_JAIL}$"; then
            echo "Jail '${SITE_JAIL}' already exists. Choose a different name."
        else
            break
        fi
    else
        echo "Jail name can only contain letters, numbers, underscores, and hyphens"
    fi
done

# Determine next available IP using jls
echo "Finding next available IP..."
USED_IPS=$(jls ip4.addr | tr -d ' ' | cut -d. -f4 | sort -n | uniq)
NEXT_IP=3
while true; do
    # Skip reserved IPs: 1 (bastille0), 2 (proxy), 10 (db), 11 (redis)
    if [ $NEXT_IP -eq 10 ] || [ $NEXT_IP -eq 11 ]; then
        NEXT_IP=12
    fi
    # Check if IP is in use
    if echo "$USED_IPS" | grep -q "^${NEXT_IP}$"; then
        NEXT_IP=$((NEXT_IP + 1))
    else
        break
    fi
done
read -p "Site jail IP [default: 10.0.0.${NEXT_IP}]: " SITE_IP
SITE_IP=${SITE_IP:-10.0.0.${NEXT_IP}}

# Domain
while true; do
    read -p "Site domain (e.g., example.com): " SITE_DOMAIN
    if [ -n "$SITE_DOMAIN" ]; then
        break
    else
        echo "Domain cannot be empty"
    fi
done

# WordPress site title
read -p "Site title [default: ${SITE_DOMAIN}]: " WP_TITLE
WP_TITLE=${WP_TITLE:-${SITE_DOMAIN}}

# WordPress admin username
read -p "Admin username [default: admin]: " WP_ADMIN_USER
WP_ADMIN_USER=${WP_ADMIN_USER:-admin}

# WordPress admin password
while true; do
    read -p "Admin password (min 8 chars): " WP_ADMIN_PASS
    if [ ${#WP_ADMIN_PASS} -ge 8 ]; then
        break
    else
        echo "Password must be at least 8 characters"
    fi
done

# WordPress admin email
while true; do
    read -p "Admin email: " WP_ADMIN_EMAIL
    if [ -n "$WP_ADMIN_EMAIL" ]; then
        break
    else
        echo "Email cannot be empty"
    fi
done

# Generate database credentials
DB_NAME=$(echo "${SITE_JAIL}" | tr '-' '_')_db
DB_USER=$(echo "${SITE_JAIL}" | tr '-' '_')_user
DB_PASS=$(openssl rand -base64 16 | tr -d '/+=' | cut -c1-16)

echo ""
echo "  Database: ${DB_NAME}"
echo "  DB User: ${DB_USER}"
echo "  DB Password: ${DB_PASS}"
echo "  Redis Database: ${NEXT_REDIS_DB}"

# DNS Configuration
echo ""
read -p "Primary DNS server [default: 1.1.1.1]: " DNS1
DNS1=${DNS1:-1.1.1.1}
read -p "Secondary DNS server [default: 8.8.8.8]: " DNS2
DNS2=${DNS2:-8.8.8.8}

# SSL options
echo ""
echo "SSL Certificate Type:"
echo "  1) Production (trusted, rate-limited)"
echo "  2) Staging (untrusted, no rate limits)"
echo "  3) Skip SSL for now"
read -p "Choose SSL type [default: 1]: " SSL_TYPE
SSL_TYPE=${SSL_TYPE:-1}
case "$SSL_TYPE" in
    2) SSL_STAGING_FLAG="--staging"; SSL_TYPE_NAME="staging" ;;
    3) SSL_TYPE_NAME="skip" ;;
    *) SSL_STAGING_FLAG=""; SSL_TYPE_NAME="production" ;;
esac

if [ "$SSL_TYPE_NAME" != "skip" ]; then
    while true; do
        read -p "Email for Let's Encrypt certificates: " CERTBOT_EMAIL
        if [ -n "$CERTBOT_EMAIL" ]; then
            break
        else
            echo "Email cannot be empty"
        fi
    done
fi

# ==========================================
# CONFIRMATION
# ==========================================

echo ""
echo "=========================================="
echo "Configuration Summary"
echo "=========================================="
echo "  Jail Name: ${SITE_JAIL}"
echo "  Jail IP: ${SITE_IP}"
echo "  Domain: ${SITE_DOMAIN}"
echo "  Site Title: ${WP_TITLE}"
echo "  Admin User: ${WP_ADMIN_USER}"
echo "  Database: ${DB_NAME}"
echo "  Redis DB: ${NEXT_REDIS_DB}"
echo "  SSL: ${SSL_TYPE_NAME}"
echo ""
read -p "Proceed with deployment? (Y/n): " CONFIRM
CONFIRM=${CONFIRM:-Y}
if [ "$CONFIRM" != "Y" ] && [ "$CONFIRM" != "y" ]; then
    echo "Deployment cancelled."
    exit 0
fi

# ==========================================
# ANSIBLE SETUP
# ==========================================

echo ""
echo "=========================================="
echo "STEP 3: Setting up Ansible"
echo "=========================================="

ANSIBLE_DIR=~/ansible-add-site-$$
mkdir -p ${ANSIBLE_DIR}
cd ${ANSIBLE_DIR}
mkdir -p roles/webserver/tasks roles/webserver/templates
mkdir -p roles/proxy_update/tasks roles/proxy_update/templates

# Create inventory
cat > inventory.ini << INVEOF
[bastille_host]
localhost ansible_connection=local

[new_site]
${SITE_JAIL} jail_ip=${SITE_IP} site_name=${SITE_JAIL} domain=${SITE_DOMAIN} db_name=${DB_NAME} db_user=${DB_USER} db_pass=${DB_PASS} wp_title="${WP_TITLE}" wp_admin_user=${WP_ADMIN_USER} wp_admin_pass=${WP_ADMIN_PASS} wp_admin_email=${WP_ADMIN_EMAIL} redis_db=${NEXT_REDIS_DB}

[all:vars]
bastille_interface=bastille0
freebsd_version=15.0-RELEASE
db_jail_ip=${DB_JAIL_IP}
redis_jail_ip=${REDIS_JAIL_IP}
proxy_jail_ip=${PROXY_JAIL_IP}
webroot_base=/usr/local/www
dns_server1=${DNS1}
dns_server2=${DNS2}
jail_type_flag=${JAIL_TYPE_FLAG}
INVEOF

# Create main playbook
cat > site.yml << 'PLAYBOOKEOF'
---
- name: Add WordPress Site to Existing Deployment
  hosts: bastille_host
  gather_facts: yes
  
  tasks:
    # PHASE 1: Create new jail
    - name: Create web jail
      command: bastille create {{ jail_type_flag }} {{ item }} {{ freebsd_version }} {{ hostvars[item].jail_ip }} {{ bastille_interface }}
      args:
        creates: /usr/local/bastille/jails/{{ item }}
      loop: "{{ groups['new_site'] }}"

    # PHASE 2: Configure DNS
    - name: Create resolv.conf
      copy:
        dest: /tmp/resolv.conf.new
        content: |
          nameserver {{ dns_server1 }}
          nameserver {{ dns_server2 }}

    - name: Copy resolv.conf to jail
      command: bastille cp {{ item }} /tmp/resolv.conf.new /etc/resolv.conf
      loop: "{{ groups['new_site'] }}"

    - name: Remove temp resolv.conf
      file:
        path: /tmp/resolv.conf.new
        state: absent

    # PHASE 3: Start jail
    - name: Start jail
      command: bastille start {{ item }}
      loop: "{{ groups['new_site'] }}"
      ignore_errors: yes

    # PHASE 4: Configure database
    - name: Create database
      command: >
        bastille cmd db0 mysql -u root -e 
        "CREATE DATABASE IF NOT EXISTS {{ hostvars[item].db_name }} 
        CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
      loop: "{{ groups['new_site'] }}"

    - name: Create database user
      command: >
        bastille cmd db0 mysql -u root -e 
        "CREATE USER IF NOT EXISTS '{{ hostvars[item].db_user }}'@'{{ hostvars[item].jail_ip }}' 
        IDENTIFIED BY '{{ hostvars[item].db_pass }}';"
      loop: "{{ groups['new_site'] }}"
      ignore_errors: yes

    - name: Grant privileges
      command: >
        bastille cmd db0 mysql -u root -e 
        "GRANT ALL PRIVILEGES ON {{ hostvars[item].db_name }}.* 
        TO '{{ hostvars[item].db_user }}'@'{{ hostvars[item].jail_ip }}';"
      loop: "{{ groups['new_site'] }}"

    - name: Flush privileges
      command: bastille cmd db0 mysql -u root -e "FLUSH PRIVILEGES;"

    # PHASE 5: Configure web jail
    - name: Configure web jail
      include_role:
        name: webserver
      vars:
        jail_name: "{{ item }}"
        jail_ip: "{{ hostvars[item].jail_ip }}"
        site_name: "{{ hostvars[item].site_name }}"
        domain: "{{ hostvars[item].domain }}"
        db_name: "{{ hostvars[item].db_name }}"
        db_user: "{{ hostvars[item].db_user }}"
        db_pass: "{{ hostvars[item].db_pass }}"
        wp_title: "{{ hostvars[item].wp_title }}"
        wp_admin_user: "{{ hostvars[item].wp_admin_user }}"
        wp_admin_pass: "{{ hostvars[item].wp_admin_pass }}"
        wp_admin_email: "{{ hostvars[item].wp_admin_email }}"
        redis_db: "{{ hostvars[item].redis_db }}"
      loop: "{{ groups['new_site'] }}"

    # PHASE 6: Update proxy configuration
    - name: Update proxy configuration
      include_role:
        name: proxy_update
      vars:
        jail_name: "{{ item }}"
        jail_ip: "{{ hostvars[item].jail_ip }}"
        domain: "{{ hostvars[item].domain }}"
      loop: "{{ groups['new_site'] }}"
PLAYBOOKEOF

# Create webserver role
cat > roles/webserver/tasks/main.yml << 'WEBEOF'
---
- name: Install packages in web jail
  command: >
    bastille pkg {{ jail_name }} install -y 
    nginx php84 php84-mysqli php84-curl php84-gd 
    php84-zip php84-zlib php84-pecl-redis php84-filter php84-ctype php84-phar php84-mbstring php84-xml php84-session php84-iconv vim

- name: Enable nginx
  command: bastille sysrc {{ jail_name }} nginx_enable=YES

- name: Enable PHP-FPM
  command: bastille sysrc {{ jail_name }} php_fpm_enable=YES

- name: Create webroot directory
  command: bastille cmd {{ jail_name }} mkdir -p {{ webroot_base }}/{{ site_name }}

- name: Download WordPress
  command: >
    bastille cmd {{ jail_name }}
    fetch -o /tmp/latest.tar.gz https://wordpress.org/latest.tar.gz

- name: Extract WordPress
  command: >
    bastille cmd {{ jail_name }}
    sh -c 'cd {{ webroot_base }}/{{ site_name }} && 
    tar -xzf /tmp/latest.tar.gz && 
    mv wordpress/* . && 
    rmdir wordpress && 
    rm /tmp/latest.tar.gz'

- name: Copy nginx config template
  template:
    src: nginx.conf.j2
    dest: /tmp/nginx_{{ jail_name }}.conf

- name: Deploy nginx config to jail
  command: bastille cp {{ jail_name }} /tmp/nginx_{{ jail_name }}.conf /usr/local/etc/nginx/nginx.conf

- name: Remove temp nginx config
  file:
    path: /tmp/nginx_{{ jail_name }}.conf
    state: absent

- name: Create wp-config.php from sample
  command: >
    bastille cmd {{ jail_name }}
    cp {{ webroot_base }}/{{ site_name }}/wp-config-sample.php 
    {{ webroot_base }}/{{ site_name }}/wp-config.php

- name: Configure database name in wp-config
  command: >
    bastille cmd {{ jail_name }}
    sed -i '' "s/database_name_here/{{ db_name }}/" 
    {{ webroot_base }}/{{ site_name }}/wp-config.php

- name: Configure database user in wp-config
  command: >
    bastille cmd {{ jail_name }}
    sed -i '' "s/username_here/{{ db_user }}/" 
    {{ webroot_base }}/{{ site_name }}/wp-config.php

- name: Configure database password in wp-config
  command: >
    bastille cmd {{ jail_name }}
    sed -i '' "s/password_here/{{ db_pass }}/" 
    {{ webroot_base }}/{{ site_name }}/wp-config.php

- name: Configure database host in wp-config
  command: >
    bastille cmd {{ jail_name }}
    sed -i '' "s/localhost/{{ db_jail_ip }}/" 
    {{ webroot_base }}/{{ site_name }}/wp-config.php

- name: Create SSL and Redis config script
  copy:
    dest: /tmp/add-config-{{ jail_name }}.sh
    content: |
      #!/bin/sh
      cd {{ webroot_base }}/{{ site_name }}
      cat > /tmp/wp-new.php << 'WPEOF'
      <?php
      /* SSL and reverse proxy settings */
      if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
          $_SERVER['HTTPS'] = 'on';
      }
      define('FORCE_SSL_ADMIN', true);
      
      /* Redis object cache settings */
      define('WP_REDIS_HOST', '{{ redis_jail_ip }}');
      define('WP_REDIS_PORT', 6379);
      define('WP_REDIS_DATABASE', {{ redis_db }});
      
      WPEOF
      tail -n +2 wp-config.php >> /tmp/wp-new.php
      mv /tmp/wp-new.php wp-config.php

- name: Copy config script to jail
  command: bastille cp {{ jail_name }} /tmp/add-config-{{ jail_name }}.sh /tmp/add-config.sh

- name: Run config script
  command: bastille cmd {{ jail_name }} sh /tmp/add-config.sh

- name: Clean up config script on host
  file:
    path: /tmp/add-config-{{ jail_name }}.sh
    state: absent

- name: Clean up config script in jail
  command: bastille cmd {{ jail_name }} rm /tmp/add-config.sh

- name: Set WordPress permissions
  command: >
    bastille cmd {{ jail_name }}
    chown -R www:www {{ webroot_base }}/{{ site_name }}

- name: Start nginx
  command: bastille service {{ jail_name }} nginx start
  ignore_errors: yes

- name: Start PHP-FPM
  command: bastille service {{ jail_name }} php_fpm start
  ignore_errors: yes

- name: Download WP-CLI
  command: >
    bastille cmd {{ jail_name }}
    fetch -o /usr/local/bin/wp https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

- name: Make WP-CLI executable
  command: bastille cmd {{ jail_name }} chmod +x /usr/local/bin/wp

- name: Wait for services to be ready
  pause:
    seconds: 3

- name: Install WordPress core
  command: >
    bastille cmd {{ jail_name }}
    sh -c 'cd {{ webroot_base }}/{{ site_name }} && /usr/local/bin/wp core install 
    --url="https://{{ domain }}" 
    --title="{{ wp_title }}" 
    --admin_user="{{ wp_admin_user }}" 
    --admin_password="{{ wp_admin_pass }}" 
    --admin_email="{{ wp_admin_email }}" 
    --skip-email 
    --allow-root'

- name: Install Redis Object Cache plugin
  command: >
    bastille cmd {{ jail_name }}
    sh -c 'cd {{ webroot_base }}/{{ site_name }} && /usr/local/bin/wp plugin install redis-cache --activate --allow-root'

- name: Enable Redis Object Cache
  command: >
    bastille cmd {{ jail_name }}
    sh -c 'cd {{ webroot_base }}/{{ site_name }} && /usr/local/bin/wp redis enable --allow-root'

- name: Set permalink structure
  command: >
    bastille cmd {{ jail_name }}
    sh -c 'cd {{ webroot_base }}/{{ site_name }} && /usr/local/bin/wp rewrite structure "/%postname%/" --allow-root'

- name: Flush rewrite rules
  command: >
    bastille cmd {{ jail_name }}
    sh -c 'cd {{ webroot_base }}/{{ site_name }} && /usr/local/bin/wp rewrite flush --allow-root'

- name: Fix permissions after WP-CLI
  command: >
    bastille cmd {{ jail_name }}
    chown -R www:www {{ webroot_base }}/{{ site_name }}
WEBEOF

# Create webserver nginx template
cat > roles/webserver/templates/nginx.conf.j2 << 'WEBNGINXEOF'
worker_processes  auto;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;
        root   {{ webroot_base }}/{{ site_name }};
        index  index.php index.html;

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

        location ~ \.php$ {
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }
    }
}
WEBNGINXEOF

# Create proxy update role
cat > roles/proxy_update/tasks/main.yml << 'PROXYEOF'
---
- name: Backup current proxy config
  command: bastille cmd proxy0 cp /usr/local/etc/nginx/nginx.conf /usr/local/etc/nginx/nginx.conf.backup.{{ ansible_date_time.epoch }}

- name: Get current proxy nginx config
  command: cat /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf
  register: current_config

- name: Create new server block file
  copy:
    dest: /tmp/new-server-block-{{ jail_name }}.conf
    content: |

          # {{ jail_name }}
          server {
              listen 80;
              http2 on;
              server_name {{ domain }};
              
              location / {
                  proxy_pass http://{{ jail_ip }};
                  proxy_set_header Host $host;
                  proxy_set_header X-Real-IP $remote_addr;
                  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                  proxy_set_header X-Forwarded-Proto $scheme;
                  proxy_set_header X-Forwarded-Host $host;
                  proxy_set_header X-Forwarded-Port $server_port;
                  
                  proxy_ignore_headers Cache-Control Expires;
                  
                  proxy_buffering on;
                  proxy_buffer_size 4k;
                  proxy_buffers 8 4k;
                  proxy_busy_buffers_size 8k;
              }
          }

- name: Check if certbot-modified config
  shell: grep -q "managed by Certbot" /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf
  register: certbot_check
  ignore_errors: yes

- name: Update proxy config (certbot-modified)
  shell: |
    # Find the line with if ($host = which indicates certbot redirect block
    REDIRECT_LINE=$(grep -n 'if (\$host = ' /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf | head -1 | cut -d: -f1)
    if [ -n "$REDIRECT_LINE" ]; then
      # Find the "server {" line before this
      SERVER_START=$((REDIRECT_LINE - 1))
      while [ $SERVER_START -gt 0 ]; do
        LINE_CONTENT=$(sed -n "${SERVER_START}p" /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf)
        if echo "$LINE_CONTENT" | grep -q "server {"; then
          break
        fi
        SERVER_START=$((SERVER_START - 1))
      done
      # Insert new block before this line
      head -n $((SERVER_START - 1)) /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf > /tmp/proxy-nginx-new.conf
      cat /tmp/new-server-block-{{ jail_name }}.conf >> /tmp/proxy-nginx-new.conf
      tail -n +${SERVER_START} /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf >> /tmp/proxy-nginx-new.conf
      cp /tmp/proxy-nginx-new.conf /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf
      rm /tmp/proxy-nginx-new.conf
    fi
  when: certbot_check.rc == 0

- name: Update proxy config (standard)
  shell: |
    # Remove last }, add server block, add } back
    head -n -1 /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf > /tmp/proxy-nginx-new.conf
    cat /tmp/new-server-block-{{ jail_name }}.conf >> /tmp/proxy-nginx-new.conf
    echo "}" >> /tmp/proxy-nginx-new.conf
    cp /tmp/proxy-nginx-new.conf /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf
    rm /tmp/proxy-nginx-new.conf
  when: certbot_check.rc != 0

- name: Remove temp server block file
  file:
    path: /tmp/new-server-block-{{ jail_name }}.conf
    state: absent

- name: Test nginx configuration
  command: bastille cmd proxy0 nginx -t
  register: nginx_test
  ignore_errors: yes

- name: Reload nginx if config valid
  command: bastille service proxy0 nginx reload
  when: nginx_test.rc == 0

- name: Restore backup if config invalid
  shell: |
    BACKUP=$(ls -t /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf.backup.* | head -1)
    cp "$BACKUP" /usr/local/bastille/jails/proxy0/root/usr/local/etc/nginx/nginx.conf
    bastille service proxy0 nginx reload
  when: nginx_test.rc != 0
PROXYEOF

echo "Ansible structure created."

# ==========================================
# RUN ANSIBLE PLAYBOOK
# ==========================================

echo ""
echo "=========================================="
echo "STEP 4: Running Ansible Deployment"
echo "=========================================="

ansible-playbook -i inventory.ini site.yml

# ==========================================
# SSL CERTIFICATE SETUP
# ==========================================

if [ "$SSL_TYPE_NAME" != "skip" ]; then
    echo ""
    echo "=========================================="
    echo "STEP 5: SSL Certificate Setup"
    echo "=========================================="
    
    echo ""
    echo "Please ensure DNS A record for ${SITE_DOMAIN} points to your server's public IP."
    read -p "Press Enter when DNS is ready (or Ctrl+C to skip SSL)... " dummy
    
    echo "Running certbot for ${SITE_DOMAIN}..."
    if bastille cmd proxy0 certbot-3.11 --nginx -d ${SITE_DOMAIN} --non-interactive --agree-tos --email ${CERTBOT_EMAIL} ${SSL_STAGING_FLAG}; then
        echo "✓ SSL certificate obtained for ${SITE_DOMAIN}"
        
        # Fix HTTP/2 after certbot
        cat > /tmp/fix-http2.sh << 'FIXSCRIPT'
#!/bin/sh
sed -i '' '/listen 443 ssl;/!b; n; /http2 on;/b; i\
        http2 on;
' /usr/local/etc/nginx/nginx.conf
nginx -t && service nginx reload
FIXSCRIPT
        bastille cp proxy0 /tmp/fix-http2.sh /tmp/fix-http2.sh
        bastille cmd proxy0 sh /tmp/fix-http2.sh
        bastille cmd proxy0 rm /tmp/fix-http2.sh
        rm /tmp/fix-http2.sh
        echo "✓ HTTP/2 enabled"
    else
        echo "✗ Failed to obtain SSL certificate"
        echo "  You can run certbot manually later:"
        echo "  bastille console proxy0"
        echo "  certbot-3.11 --nginx -d ${SITE_DOMAIN} ${SSL_STAGING_FLAG}"
    fi
fi

# ==========================================
# CLEANUP ANSIBLE FILES
# ==========================================

cd ~
rm -rf ${ANSIBLE_DIR}

# ==========================================
# SUMMARY
# ==========================================

echo ""
echo "=========================================="
echo "DEPLOYMENT COMPLETE!"
echo "=========================================="
echo ""
echo "Site Details:"
echo "  Jail Name: ${SITE_JAIL}"
echo "  Jail IP: ${SITE_IP}"
echo "  Domain: ${SITE_DOMAIN}"
echo "  URL: https://${SITE_DOMAIN}"
echo "  Admin URL: https://${SITE_DOMAIN}/wp-admin"
echo ""
echo "WordPress Admin:"
echo "  Username: ${WP_ADMIN_USER}"
echo "  Password: ${WP_ADMIN_PASS}"
echo "  Email: ${WP_ADMIN_EMAIL}"
echo ""
echo "Database:"
echo "  Name: ${DB_NAME}"
echo "  User: ${DB_USER}"
echo "  Password: ${DB_PASS}"
echo "  Host: ${DB_JAIL_IP}"
echo ""
echo "Redis:"
echo "  Host: ${REDIS_JAIL_IP}"
echo "  Port: 6379"
echo "  Database: ${NEXT_REDIS_DB}"
echo ""
echo "Features Enabled:"
echo "  ✓ Redis Object Cache"
echo "  ✓ Pretty permalinks (/%postname%/)"
if [ "$SSL_TYPE_NAME" != "skip" ]; then
echo "  ✓ SSL certificate (${SSL_TYPE_NAME})"
fi
echo ""
echo "=========================================="
echo "TESTING COMMANDS"
echo "=========================================="
echo ""
echo "# Hairpin NAT: Use proxy jail IP with Host header"
echo "curl -sI -k -H \"Accept-Encoding: gzip\" https://${PROXY_JAIL_IP} -H \"Host: ${SITE_DOMAIN}\" | grep -E \"HTTP|content-encoding\""
echo ""
echo "# Redis tests"
echo "bastille cmd redis0 redis-cli ping"
echo "bastille cmd redis0 redis-cli info keyspace"
echo "grep WP_REDIS_DATABASE /usr/local/bastille/jails/${SITE_JAIL}/root/usr/local/www/${SITE_JAIL}/wp-config.php"
echo ""
echo "# Nginx config check"
echo "bastille cmd proxy0 nginx -t"
echo ""
echo "=========================================="
echo "IF SCRIPT FAILS MID-WAY - CLEANUP"
echo "=========================================="
echo ""
echo "bastille destroy -fay ${SITE_JAIL}"
echo "bastille cmd db0 mysql -u root -e \"DROP USER IF EXISTS '${DB_USER}'@'${SITE_IP}';\""
echo "bastille cmd db0 mysql -u root -e \"DROP DATABASE IF EXISTS ${DB_NAME};\""
echo ""
echo "=========================================="

MAINSCRIPT

chmod +x add-wordpress-site-v6.sh
