#!/usr/bin/env bash

set -Eeuo pipefail

EXPECTED_HOST=${EXPECTED_HOST:-sqjcnginx01}
BUNDLE_ROOT=${BUNDLE_ROOT:-/opt/zhct-deploy}
BACKUP_ROOT=${BACKUP_ROOT:-/var/backups/zhct-q040/20260722T203557+0800}
QUARANTINE_ROOT="$BACKUP_ROOT/quarantined-framework-metadata"
EVIDENCE_DIR="$BACKUP_ROOT/evidence"
INVENTORY="$EVIDENCE_DIR/quarantined-framework-metadata.tsv"

[[ $(hostname -s) == "$EXPECTED_HOST" ]] || {
    echo "unexpected host: $(hostname -s)" >&2
    exit 1
}

roots=("$BUNDLE_ROOT/common" "$BUNDLE_ROOT/roles/nginx")
for root in "${roots[@]}"; do
    [[ -d "$root" ]] || { echo "framework directory missing: $root" >&2; exit 1; }
done

install -d -m 0700 "$QUARANTINE_ROOT" "$EVIDENCE_DIR"
printf 'sha256\tbytes\tfile_type\tsource\tquarantine\n' >"$INVENTORY"

count=0
while IFS= read -r -d '' source; do
    relative=${source#"$BUNDLE_ROOT/"}
    destination="$QUARANTINE_ROOT/$relative"
    install -d -m 0700 "$(dirname "$destination")"
    digest=$(sha256sum "$source" | awk '{print $1}')
    bytes=$(stat -c '%s' "$source")
    file_type=$(file -b "$source" | tr '\t\n' '  ')
    printf '%s\t%s\t%s\t%s\t%s\n' \
        "$digest" "$bytes" "$file_type" "$source" "$destination" >>"$INVENTORY"
    mv "$source" "$destination"
    count=$((count + 1))
done < <(find "${roots[@]}" -type f \( -name '._*' -o -name '.DS_Store' \) -print0)

remaining=$(find "${roots[@]}" -type f \( -name '._*' -o -name '.DS_Store' \) -print -quit)
[[ -z "$remaining" ]] || { echo "metadata artifact remains: $remaining" >&2; exit 1; }

while IFS= read -r -d '' script; do
    bash -n "$script"
done < <(find "${roots[@]}" -type f -name '*.sh' -print0)

chmod 0600 "$INVENTORY"
printf 'Q040_FRAMEWORK_METADATA_QUARANTINE_OK\n'
printf 'QUARANTINED_COUNT=%s\n' "$count"
printf 'INVENTORY=%s\n' "$INVENTORY"
