#!/bin/sh
set -eu
umask 077

project=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
runtime=${TIDELATHE_RUNTIME:-"$project/.local"}
port=${TIDELATHE_PORT:-8237}
mkdir -p "$runtime"
runtime=$(CDPATH='' cd -- "$runtime" && pwd)
downloads="$runtime/downloads"
docroot="$runtime/wordpress"
local_php="$runtime/bin/php"
wp_phar="$downloads/wp-cli-2.12.0.phar"
local_url="http://127.0.0.1:$port"
action=${1:-help}

die() { printf '%s\n' "$*" >&2; exit 1; }

download() {
    archive="$downloads/$1"
    if [ ! -s "$archive" ]; then
        printf 'Fetching %s\n' "$1" >&2
        curl --fail --location --silent --show-error --retry 2 "$3" -o "$archive.part"
        mv "$archive.part" "$archive"
    fi
    printf '%s  %s\n' "$2" "$archive" | shasum -a 256 -c - >/dev/null ||
        die "Checksum mismatch for $archive. Remove that cache file and retry."
}

choose_php() {
    if [ -n "${TIDELATHE_PHP:-}" ]; then
        php_bin=$TIDELATHE_PHP
    elif [ -x "$local_php" ]; then
        php_bin=$local_php
    elif command -v php >/dev/null 2>&1 && php_has_extensions php; then
        php_bin=php
    elif [ "$action" = setup ] && [ "$(uname -s)/$(uname -m)" = Darwin/arm64 ]; then
        download php-8.4.28-cli-macos-aarch64.tar.gz 998bdd58bc6a04ae41b72c0e21da6103f0296f214e1e77bd3265355e4723bcc3 https://dl.static-php.dev/v3/php-bin/common/php-8.4.28-cli-macos-aarch64.tar.gz
        mkdir -p "$runtime/bin"
        tar -xzf "$archive" -C "$runtime/bin" php
        php_bin=$local_php
    else
        die 'Use PHP 8.0+ with PDO SQLite and GD WebP support, or run setup on Apple Silicon to fetch the project-local binary.'
    fi
    php_has_extensions "$php_bin" || die 'The selected PHP needs PDO SQLite and GD WebP support.'
}

php_has_extensions() {
    "$1" -r 'exit(PHP_VERSION_ID >= 80000 && extension_loaded("pdo_sqlite") && function_exists("imagewebp") ? 0 : 1);'
}

wp_cli() {
    HTTP_HOST="127.0.0.1:$port" WP_CLI_CONFIG_PATH=/dev/null WP_CLI_CACHE_DIR="$runtime/cache" \
        "$php_bin" "$wp_phar" --path="$docroot" --skip-packages "$@"
}

create_config() {
    {
        cat <<'PHP'
define( 'WP_ENVIRONMENT_TYPE', 'local' );
define( 'WP_HTTP_BLOCK_EXTERNAL', true );
define( 'AUTOMATIC_UPDATER_DISABLED', true );
define( 'DISABLE_WP_CRON', true );
define( 'DISALLOW_FILE_EDIT', true );
PHP
        "$php_bin" -r '
            foreach (["AUTH_KEY","SECURE_AUTH_KEY","LOGGED_IN_KEY","NONCE_KEY","AUTH_SALT","SECURE_AUTH_SALT","LOGGED_IN_SALT","NONCE_SALT"] as $name) {
                printf("define( %s, %s );\n", var_export($name, true), var_export(bin2hex(random_bytes(32)), true));
            }'
    } | wp_cli config create --dbname=tidelathe --dbuser=sqlite --skip-check --skip-salts --extra-php
}

setup() {
    mkdir -p "$downloads" "$docroot"
    choose_php

    download wp-cli-2.12.0.phar ce34ddd838f7351d6759068d09793f26755463b4a4610a5a5c0a97b68220d85c https://github.com/wp-cli/wp-cli/releases/download/v2.12.0/wp-cli-2.12.0.phar
    if [ ! -f "$runtime/.core-7.1.5" ]; then
        download wordpress-7.1.5.tar.gz 053857d980eaee8702c617c685948becb9be2523ba0dcbc98e4dbb2300367c79 https://wordpress.org/wordpress-7.1.5.tar.gz
        tar -xzf "$archive" --strip-components=1 -C "$docroot"
        touch "$runtime/.core-7.1.5"
    fi

    plugins="$docroot/wp-content/plugins"
    if [ ! -f "$plugins/sqlite-database-integration/db.copy" ]; then
        download sqlite-database-integration.3.1.3.zip f6ce35e8419d0b9326221a907627d905e25c2a5ba2afc86492811f14c851efe0 https://downloads.wordpress.org/plugin/sqlite-database-integration.3.1.3.zip
        unzip -oq "$archive" -d "$plugins"
    fi
    if [ ! -f "$plugins/secure-custom-fields/secure-custom-fields.php" ]; then
        download secure-custom-fields.6.9.10.zip 59544690a84ed09c18a0b0425fa6ffa08a58d47bd4337ab0ccc36b518a5e4937 https://downloads.wordpress.org/plugin/secure-custom-fields.6.9.10.zip
        unzip -oq "$archive" -d "$plugins"
    fi
    if [ ! -f "$docroot/wp-content/db.php" ]; then
        cp "$plugins/sqlite-database-integration/db.copy" "$docroot/wp-content/db.php"
    fi
    [ -f "$docroot/wp-config.php" ] || create_config

    if ! wp_cli core is-installed; then
        if [ ! -s "$runtime/admin-password" ]; then
            "$php_bin" -r 'echo bin2hex(random_bytes(18)), "\n";' > "$runtime/admin-password"
        fi
        wp_cli core install --url="$local_url" --title=Tidelathe --admin_user=tidelathe-editor \
            --admin_email=editor@tidelathe.example --skip-email --admin_password="$(cat "$runtime/admin-password")"
        wp_cli option update blog_public 0
        wp_cli option update show_avatars 0
        wp_cli rewrite structure '/%postname%/'
    fi
    [ "$(wp_cli option get home)" = "$local_url" ] ||
        die 'This runtime is assigned to another port. Use its original TIDELATHE_PORT or choose a new TIDELATHE_RUNTIME.'

    theme_link="$docroot/wp-content/themes/tidelathe"
    if [ ! -e "$theme_link" ] && [ ! -L "$theme_link" ]; then
        ln -s "$project/theme/tidelathe" "$theme_link"
    fi
    if [ "$(readlink "$theme_link")" != "$project/theme/tidelathe" ]; then
        die "The local theme link points elsewhere: $theme_link"
    fi
    if [ ! -e "$docroot/email" ] && [ ! -L "$docroot/email" ]; then
        ln -s "$project/email" "$docroot/email"
    fi

    wp_cli plugin activate secure-custom-fields
    wp_cli theme activate tidelathe
    wp_cli eval-file "$project/scripts/seed.php" --user=tidelathe-editor
    wp_cli eval-file "$project/scripts/seed-editorial.php" --user=tidelathe-editor
    printf 'Ready at %s. Run %s serve.\n' "$local_url" "$0"
}

case "$action" in
    setup) setup ;;
    serve)
        [ -f "$docroot/wp-config.php" ] || die 'Run setup first.'
        choose_php
        [ "$(wp_cli option get home)" = "$local_url" ] || die 'Use the port chosen during setup.'
        printf 'Studio  %s/\nEmail   %s/email/preview.html\n' "$local_url" "$local_url"
        exec "$php_bin" -d sendmail_path=/usr/bin/true -S "127.0.0.1:$port" -t "$docroot" "$project/scripts/router.php"
        ;;
    wp)
        shift
        [ -f "$wp_phar" ] || die 'Run setup first.'
        choose_php
        wp_cli "$@"
        ;;
    credentials)
        [ -s "$runtime/admin-password" ] || die 'Run setup first.'
        printf 'Login     %s/wp-login.php\nUsername  tidelathe-editor\nPassword  ' "$local_url"
        cat "$runtime/admin-password"
        ;;
    *) printf 'Usage: %s {setup|serve|wp|credentials}\n' "$0" ;;
esac
