#!/usr/bin/env bash
set -euo pipefail

readonly IPZ_SNAPSHOT_CONTRACT_VERSION=1
readonly IPZ_WORDPRESS_IMAGE='docker.io/library/wordpress:6.6-php8.2-apache'
readonly IPZ_WORDPRESS_CLI_IMAGE='docker.io/library/wordpress:cli-php8.2'
readonly IPZ_MARIADB_IMAGE='docker.io/library/mariadb:11'
readonly IPZ_ACF_VERSION='6.3.5'
readonly IPZ_FIXTURE_SCHEMA_VERSION='acf-fields-v1'
readonly IPZ_PHP_REQUIREMENT='>=8.2'
readonly IPZ_DATABASE_SCHEMA='wordpress-core-6.6'

ipz_snapshot_fingerprint_input() {
    printf '%s\n' \
        "contract=${IPZ_SNAPSHOT_CONTRACT_VERSION}" \
        "wordpress=${IPZ_WORDPRESS_IMAGE}" \
        "mariadb=${IPZ_MARIADB_IMAGE}" \
        "database_schema=${IPZ_DATABASE_SCHEMA}" \
        "php=${IPZ_PHP_REQUIREMENT}" \
        "acf=${IPZ_ACF_VERSION}" \
        "fixtures=${IPZ_FIXTURE_SCHEMA_VERSION}"
}

ipz_snapshot_fingerprint() {
    ipz_snapshot_fingerprint_input | sha256sum | cut -d' ' -f1
}

ipz_snapshot_root() {
    printf '%s\n' "${IPZ_E2E_SNAPSHOT_ROOT:-${HOME}/.cache/presszone/e2e-snapshots}"
}

ipz_snapshot_dir() {
    printf '%s/%s\n' "$(ipz_snapshot_root)" "$(ipz_snapshot_fingerprint)"
}

ipz_snapshot_rebuild_command() {
    printf './tests/e2e/build-e2e-snapshot.sh\n'
}

ipz_snapshot_reject() {
    printf 'E2E snapshot is missing or incompatible. Rebuild exactly with: %s\n' "$(ipz_snapshot_rebuild_command)" >&2
    return 1
}

ipz_validate_snapshot() {
    local directory=${1:-"$(ipz_snapshot_dir)"} expected actual
    expected="$(ipz_snapshot_fingerprint_input)"
    [[ -d "${directory}" && -f "${directory}/fingerprint" && -f "${directory}/contract" \
        && -f "${directory}/database.tar" && -f "${directory}/wordpress.tar" ]] || {
        ipz_snapshot_reject
        return 1
    }
    actual="$(<"${directory}/fingerprint")"
    [[ "${actual}" == "$(ipz_snapshot_fingerprint)" ]] || {
        ipz_snapshot_reject
        return 1
    }
    [[ "$(<"${directory}/contract")" == "${expected}" ]] || {
        ipz_snapshot_reject
        return 1
    }
    if tar -tf "${directory}/wordpress.tar" | grep -Eq '(^|/)wp-content/plugins/international-press-zone(/|$)'; then
        printf 'E2E snapshot illegally contains current plugin source. Rebuild exactly with: %s\n' "$(ipz_snapshot_rebuild_command)" >&2
        return 1
    fi
}
