#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

LABEL=REDIS01_Q131_SECRET_METADATA_DIAGNOSIS
EXPECTED_HOST=sqjcredis01
EXPECTED_IP=10.2.203.112
RUN_ID="q131-secret-metadata-$(date +%Y%m%dT%H%M%S%z)"
AUDIT_DIR="/var/backups/zhct-manual-preflight/${RUN_ID}"
AUDIT_LOG="${AUDIT_DIR}/operator.log"

finish() {
    rc=$?
    trap - EXIT
    printf 'END|%s|RC=%s|AUDIT_LOG=%s\n' \
        "$LABEL" "$rc" "${AUDIT_LOG:-NOT_CREATED}"
    exit "$rc"
}
trap finish EXIT

printf 'BEGIN|%s|%s\n' "$LABEL" "$(date --iso-8601=seconds)"
actual_host=$(hostname -s)
printf 'IDENTITY|hostname=%s|expected=%s\n' "$actual_host" "$EXPECTED_HOST"
test "$actual_host" = "$EXPECTED_HOST"
ip -o -4 addr show scope global |
    awk '{split($4,a,"/"); print a[1]}' |
    grep -Fxq "$EXPECTED_IP"

install -d -o root -g root -m 0700 "$AUDIT_DIR"
exec > >(tee -a "$AUDIT_LOG") 2>&1
printf 'AUDIT_BEGIN|%s|%s\n' "$LABEL" "$(date --iso-8601=seconds)"

printf '%s\n' '=== DIRECTORY METADATA ==='
for path in /etc/zhct /etc/zhct/secrets; do
    if test -e "$path" || test -L "$path"; then
        stat -c 'DIRECTORY|PRESENT|%F|%A|%a|%U:%G|%n' "$path"
    else
        printf 'DIRECTORY|ABSENT|%s\n' "$path"
    fi
done

overall=PASS
printf '%s\n' '=== SECRET FILE METADATA ONLY ==='
for file in \
    /etc/zhct/secrets/redis5.password \
    /etc/zhct/secrets/redis7.password
do
    if ! test -e "$file" && ! test -L "$file"; then
        printf 'SECRET|ABSENT|%s\n' "$file"
        overall=BLOCKED
        continue
    fi
    if test -L "$file"; then
        printf 'SECRET|BLOCKED_SYMLINK|%s\n' "$file"
        overall=BLOCKED
        continue
    fi
    stat -c 'SECRET|PRESENT|%F|%A|%a|%U:%G|%s bytes|%n' "$file"
    nonempty=NO
    test -s "$file" && nonempty=YES
    line_count=$(awk 'END {print NR+0}' "$file")
    printf 'SECRET_CHECK|%s|nonempty=%s|lines=%s\n' \
        "$file" "$nonempty" "$line_count"
    owner=$(stat -c %U:%G "$file")
    mode=$(stat -c %a "$file")
    if test "$nonempty" != YES ||
       test "$line_count" -ne 1 ||
       test "$owner" != root:root ||
       { test "$mode" != 400 && test "$mode" != 600; }
    then
        overall=BLOCKED
    fi
done

if test "$overall" = PASS; then
    echo 'Q131_SECRET_METADATA_GATE=PASS'
    echo 'DIAGNOSTIC_ONLY=PASS_NO_SECRET_CONTENT_OUTPUT'
else
    echo 'Q131_SECRET_METADATA_GATE=BLOCKED'
    echo 'DIAGNOSTIC_ONLY=PASS_NO_SECRET_CONTENT_OUTPUT'
    exit 3
fi
