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

readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=e2e-snapshot-contract.sh
source "${SCRIPT_DIR}/e2e-snapshot-contract.sh"
workspace="$(mktemp -d "${TMPDIR:-/tmp}/ipz snapshot test.XXXXXX")"
trap 'rm -rf -- "${workspace}"' EXIT
export IPZ_E2E_SNAPSHOT_ROOT="${workspace}/root with spaces"
snapshot="$(ipz_snapshot_dir)"
expected='E2E snapshot is missing or incompatible. Rebuild exactly with: ./tests/e2e/build-e2e-snapshot.sh'

assert_rejected() {
    local output
    if output="$(ipz_validate_snapshot "${snapshot}" 2>&1)"; then
        printf 'Invalid snapshot was accepted.\n' >&2
        exit 1
    fi
    [[ "${output}" == "${expected}" ]] || { printf 'Unexpected rebuild instruction: %s\n' "${output}" >&2; exit 1; }
}

assert_rejected
mkdir -p "${snapshot}" "${workspace}/wordpress/wp-content/plugins/advanced-custom-fields" "${workspace}/database/mysql"
printf data >"${workspace}/wordpress/index.php"
printf data >"${workspace}/database/mysql/data"
tar -C "${workspace}/wordpress" -cf "${snapshot}/wordpress.tar" .
tar -C "${workspace}/database" -cf "${snapshot}/database.tar" .
ipz_snapshot_fingerprint >"${snapshot}/fingerprint"
ipz_snapshot_fingerprint_input >"${snapshot}/contract"
ipz_validate_snapshot "${snapshot}"

printf mismatch >"${snapshot}/fingerprint"
assert_rejected
ipz_snapshot_fingerprint >"${snapshot}/fingerprint"
mkdir -p "${workspace}/wordpress/wp-content/plugins/international-press-zone"
printf source >"${workspace}/wordpress/wp-content/plugins/international-press-zone/plugin.php"
tar -C "${workspace}/wordpress" -cf "${snapshot}/wordpress.tar" .
plugin_output="$(ipz_validate_snapshot "${snapshot}" 2>&1 || true)"
[[ "${plugin_output}" == 'E2E snapshot illegally contains current plugin source. Rebuild exactly with: ./tests/e2e/build-e2e-snapshot.sh' ]] || {
    printf 'Plugin exclusion rejection failed: %s\n' "${plugin_output}" >&2
    exit 1
}

remote="$(<"${SCRIPT_DIR}/remote-stack.sh")"
[[ "${remote}" != *'wp core install'* && "${remote}" != *'wp plugin install advanced-custom-fields'* ]] || {
    printf 'Runtime still performs baseline installation.\n' >&2
    exit 1
}
[[ "${remote}" == *'tar -C /restore -xf /snapshot/database.tar'* && "${remote}" == *'tar -C /restore -xf /snapshot/wordpress.tar'* ]] || {
    printf 'Runtime does not restore both disposable volumes.\n' >&2
    exit 1
}
[[ "${remote}" == *'trap cleanup EXIT INT TERM'* && "${remote}" == *'podman wait "${WORDPRESS_CONTAINER}"'* ]] || {
    printf 'Runtime lifecycle does not preserve stack or clean failures.\n' >&2
    exit 1
}
printf 'snapshot contract tests: PASS\n'
