#!/bin/bash
# =============================================================================
# WordPress auto-setup for IOTA Web Guardian demo.
#
# This script runs inside the WordPress container on first boot:
#   1. Waits for the database
#   2. Installs WordPress (admin user, site title)
#   3. Activates the IOTA Web Guardian plugin
#   4. Pre-configures plugin settings (CVS, x402 URLs, etc.)
#
# On subsequent boots it detects WP is already installed and skips setup.
# =============================================================================

set -e

# Install WP-CLI if not present
if ! command -v wp &> /dev/null; then
    echo "[guardian-init] Installing WP-CLI..."
    curl -sO https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
    chmod +x wp-cli.phar
    mv wp-cli.phar /usr/local/bin/wp
fi

# Wait for WordPress files to be ready (docker-entrypoint may still be copying)
echo "[guardian-init] Waiting for WordPress files..."
for i in $(seq 1 30); do
    if [ -f /var/www/html/wp-includes/version.php ]; then
        break
    fi
    sleep 2
done

# Wait for database
echo "[guardian-init] Waiting for database..."
for i in $(seq 1 30); do
    if wp db check --allow-root --path=/var/www/html 2>/dev/null; then
        break
    fi
    sleep 2
done

# Check if WP is already installed
if wp core is-installed --allow-root --path=/var/www/html 2>/dev/null; then
    echo "[guardian-init] WordPress already installed — skipping setup."
else
    echo "[guardian-init] Installing WordPress..."
    wp core install \
        --allow-root \
        --path=/var/www/html \
        --url="http://localhost:8090" \
        --title="IOTA Web Guardian Demo" \
        --admin_user=admin \
        --admin_password=admin \
        --admin_email=admin@example.com \
        --locale=en_US \
        --skip-email

    # Enable pretty permalinks
    echo "[guardian-init] Enabling pretty permalinks..."
    wp rewrite structure '/%postname%/' --allow-root --path=/var/www/html
    wp rewrite flush --allow-root --path=/var/www/html

    echo "[guardian-init] Creating demo content..."

    # Post 1: Premium article
    wp post update 1 \
        --allow-root \
        --path=/var/www/html \
        --post_name="the-future-of-ai-content-licensing" \
        --post_title="The Future of AI Content Licensing" \
        --post_content="<h2>Why Content Creators Need On-Chain Protection</h2><p>As AI models consume ever-larger swaths of the internet for training data, content creators face an existential question: how do you get compensated when your work fuels billion-dollar models?</p><p>IOTA Web Guardian introduces a novel approach: <strong>micropayments per request</strong>, verified on the IOTA Tangle. Every AI agent must present a Verifiable Credential (proving its identity) and pay a small fee before accessing protected content. Human browsers pass through freely — zero friction.</p><h2>How It Works</h2><p>The Guardian pipeline is simple: <code>401 → VP → 402 → payment → 200</code>. The agent proves who it is (via a DID-based Verifiable Presentation), then pays the content creator directly on IOTA Layer 1. No intermediaries, no subscriptions — just transparent, per-use compensation.</p><p>This is the future of ethical AI training: creators get paid, agents get data, and the blockchain keeps everyone honest.</p>"

    # Post 2: Tutorial
    wp post create \
        --allow-root \
        --path=/var/www/html \
        --post_type=post \
        --post_status=publish \
        --post_title="Getting Started with IOTA Identity" \
        --post_content="<h2>What is IOTA Identity?</h2><p>IOTA Identity is a framework for creating and managing <strong>Decentralized Identifiers (DIDs)</strong> and <strong>Verifiable Credentials (VCs)</strong> anchored on the IOTA Tangle. Unlike traditional identity systems, DIDs are self-sovereign — the holder controls their own identity without relying on a central authority.</p><h2>The Trust Chain</h2><p>In the IOTA Web Guardian ecosystem, trust flows through a chain:</p><ol><li><strong>Super Certifier</strong> — the root of trust, publishes its DID on-chain</li><li><strong>Certifier</strong> — approved by the Super Certifier, issues VCs to agents</li><li><strong>AI Agent</strong> — registers, receives a VC, uses it to access protected content</li></ol><p>Each entity has an on-chain DID Document containing its public key and verification methods. The CVS (Certificate Verifier Service) can resolve any DID and verify the entire trust chain in milliseconds.</p><h2>Try It Yourself</h2><p>Follow the <a href='https://github.com/your-org/iota-web-guardian'>README</a> to set up a local environment and register your first AI agent. The entire flow — from DID creation to content access — takes under 5 minutes.</p>"

    # Post 3: Market data
    wp post create \
        --allow-root \
        --path=/var/www/html \
        --post_type=post \
        --post_status=publish \
        --post_title="Premium Market Data Q1 2026" \
        --post_content="<h2>IOTA Ecosystem Growth Report</h2><p>The IOTA ecosystem saw remarkable growth in Q1 2026, driven by the launch of the Move VM and the expansion of DeFi protocols on the network.</p><h3>Key Metrics</h3><table><tr><th>Metric</th><th>Q4 2025</th><th>Q1 2026</th><th>Growth</th></tr><tr><td>Active Addresses</td><td>142,000</td><td>287,000</td><td>+102%</td></tr><tr><td>Daily Transactions</td><td>1.2M</td><td>3.8M</td><td>+217%</td></tr><tr><td>Total Value Locked</td><td>\$45M</td><td>\$189M</td><td>+320%</td></tr><tr><td>DID Documents Created</td><td>8,400</td><td>34,200</td><td>+307%</td></tr></table><p>The introduction of Verifiable Credentials for AI agent authentication has been a key driver, with over 12,000 agents registered in the first quarter alone. Content creators using IOTA Web Guardian have earned a combined 2.4M IOTA in micropayments.</p><p><em>This premium dataset is protected by IOTA Web Guardian. AI agents must present valid credentials and pay per-access.</em></p>"
fi

# Activate theme + plugin (idempotent)
echo "[guardian-init] Activating IOTA Guardian theme..."
wp theme activate iota-guardian-theme --allow-root --path=/var/www/html 2>/dev/null || true

echo "[guardian-init] Activating IOTA Web Guardian plugin..."
wp plugin activate iota-guardian-wp --allow-root --path=/var/www/html 2>/dev/null || true

# Configure plugin settings (idempotent — overwrites each time to ensure correct URLs)
echo "[guardian-init] Configuring plugin settings..."
wp option update iota_guardian_options \
    --allow-root \
    --path=/var/www/html \
    --format=json \
    '{"enabled":true,"jwt_secret":"'"$(head -c 32 /dev/urandom | base64 | tr -d '=/+'| head -c 32)"'","token_ttl":60,"cvs_url":"http://host.docker.internal:8081","x402_url":"http://host.docker.internal:8082","payment_amount":1000,"payment_address":"'"${GUARDIAN_PAYMENT_RECIPIENT:-0x0000000000000000000000000000000000000000000000000000000000000000}"'"}'

echo "[guardian-init] Done! WordPress is ready at http://localhost:8090"
echo "[guardian-init] Admin login: admin / admin"
