#!/usr/bin/env bash
# REVOKED_DO_NOT_UPLOAD_OR_EXECUTE
# Reason: Q-131/Q-132 must import the canonical same-source Redis secrets
# exported from the Nginx role; interactive creation would break the
# HAProxy/Sentinel/Redis authentication contract.
set -Eeuo pipefail
set +x
umask 077

LABEL=REDIS01_Q131_PROVISION_REDIS_SECRETS
EXPECTED_HOST=sqjcredis01
EXPECTED_IP=10.2.203.112
SECRET_DIR=/etc/zhct/secrets
REDIS5_FILE="$SECRET_DIR/redis5.password"
REDIS7_FILE="$SECRET_DIR/redis7.password"
RUN_ID="q131-provision-secrets-$(date +%Y%m%dT%H%M%S%z)"
AUDIT_DIR="/var/backups/zhct-manual-preflight/${RUN_ID}"
AUDIT_LOG="${AUDIT_DIR}/operator.log"
tmp5=
tmp7=
target5_written=0
target7_written=0
success=0
REDIS5_PASSWORD=
REDIS5_CONFIRM=
REDIS7_PASSWORD=
REDIS7_CONFIRM=

finish() {
    rc=$?
    trap - EXIT
    set +e
    test -n "$tmp5" && rm -f -- "$tmp5"
    test -n "$tmp7" && rm -f -- "$tmp7"
    if test "$rc" -ne 0 && test "$success" -ne 1; then
        test "$target5_written" -eq 1 && rm -f -- "$REDIS5_FILE"
        test "$target7_written" -eq 1 && rm -f -- "$REDIS7_FILE"
    fi
    REDIS5_PASSWORD=
    REDIS5_CONFIRM=
    REDIS7_PASSWORD=
    REDIS7_CONFIRM=
    unset REDIS5_PASSWORD REDIS5_CONFIRM REDIS7_PASSWORD REDIS7_CONFIRM
    printf 'END|%s|RC=%s|AUDIT_LOG=%s\n' \
        "$LABEL" "$rc" "${AUDIT_LOG:-NOT_CREATED}"
    exit "$rc"
}
trap finish EXIT

die() {
    printf 'ERROR|%s\n' "$*" >&2
    return 1
}

validate_secret() {
    local name=$1 value=$2
    test -n "$value" || die "$name is empty"
    case "$value" in
        *[[:space:]]*|*\\*|*\"*|*\'*)
            die "$name contains whitespace, quote, or backslash unsupported by Redis config materialization"
            ;;
    esac
}

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"
test -r /dev/tty
test -w /dev/tty

test ! -e "$REDIS5_FILE"
test ! -L "$REDIS5_FILE"
test ! -e "$REDIS7_FILE"
test ! -L "$REDIS7_FILE"

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)"
echo 'SECRET_INPUT_POLICY=TTY_HIDDEN_CONFIRMATION_NO_VALUE_OUTPUT'

printf 'Enter customer-approved Redis5 password: ' >/dev/tty
IFS= read -r -s REDIS5_PASSWORD </dev/tty
printf '\nConfirm Redis5 password: ' >/dev/tty
IFS= read -r -s REDIS5_CONFIRM </dev/tty
printf '\n' >/dev/tty
test "$REDIS5_PASSWORD" = "$REDIS5_CONFIRM" ||
    die 'Redis5 password confirmation mismatch'
validate_secret REDIS5_PASSWORD "$REDIS5_PASSWORD"

printf 'Enter customer-approved Redis7 password: ' >/dev/tty
IFS= read -r -s REDIS7_PASSWORD </dev/tty
printf '\nConfirm Redis7 password: ' >/dev/tty
IFS= read -r -s REDIS7_CONFIRM </dev/tty
printf '\n' >/dev/tty
test "$REDIS7_PASSWORD" = "$REDIS7_CONFIRM" ||
    die 'Redis7 password confirmation mismatch'
validate_secret REDIS7_PASSWORD "$REDIS7_PASSWORD"

install -d -o root -g root -m 0700 "$SECRET_DIR"
tmp5=$(mktemp "$SECRET_DIR/.redis5.password.XXXXXX")
tmp7=$(mktemp "$SECRET_DIR/.redis7.password.XXXXXX")
chmod 0600 "$tmp5" "$tmp7"
printf '%s\n' "$REDIS5_PASSWORD" >"$tmp5"
printf '%s\n' "$REDIS7_PASSWORD" >"$tmp7"
REDIS5_PASSWORD=
REDIS5_CONFIRM=
REDIS7_PASSWORD=
REDIS7_CONFIRM=
unset REDIS5_PASSWORD REDIS5_CONFIRM REDIS7_PASSWORD REDIS7_CONFIRM

install -o root -g root -m 0600 "$tmp5" "$REDIS5_FILE"
target5_written=1
install -o root -g root -m 0600 "$tmp7" "$REDIS7_FILE"
target7_written=1
rm -f -- "$tmp5" "$tmp7"
tmp5=
tmp7=

for file in "$REDIS5_FILE" "$REDIS7_FILE"; do
    test -s "$file"
    test ! -L "$file"
    test "$(stat -c %U:%G "$file")" = root:root
    test "$(stat -c %a "$file")" = 600
    test "$(awk 'END {print NR+0}' "$file")" -eq 1
    stat -c 'SECRET_METADATA|PRESENT_NONEMPTY|%A|%U:%G|%s bytes|%n' "$file"
done

success=1
echo 'Q131_REDIS_SECRET_PROVISIONING=PASS_VALUES_NOT_OUTPUT'
echo 'NEXT_ACTION=RERUN_Q131_EXECUTE_READINESS'
