#!/usr/bin/env bash
# whp-unlock-data-drive — admin CLI wrapper for the LUKS unlock helper.
# Prompts for the passphrase on tty (no echo), pipes to
# whp-luks-unlock-helper.sh, prints a human-readable result.
#
# For scripted/non-interactive use, pipe the passphrase directly to the helper:
#   echo "$PASSPHRASE" | /root/whp/scripts/whp-luks-unlock-helper.sh

set -euo pipefail

SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
HELPER="$SCRIPT_DIR/whp-luks-unlock-helper.sh"
LIB="$SCRIPT_DIR/lib-luks-state.sh"

if [ ! -x "$HELPER" ]; then
    echo "ERROR: helper not found at $HELPER" >&2
    exit 1
fi
if [ ! -f "$LIB" ]; then
    echo "ERROR: lib not found at $LIB" >&2
    exit 1
fi

# shellcheck disable=SC1090
. "$LIB"

echo "WHP /docker LUKS unlock"
echo

if ! luks_is_enabled; then
    echo "  LUKS is not configured on this server."
    echo "  Nothing to unlock."
    exit 0
fi

echo "  Device:     ${LUKS_BACKING_DEVICE}"
echo "  Mapper:     /dev/mapper/${LUKS_MAPPER_NAME}"
echo "  Mountpoint: ${LUKS_MOUNT_POINT}"

if luks_is_unlocked; then
    echo "  Status:     UNLOCKED (already mounted)"
    echo
    echo "Nothing to do."
    exit 0
fi

echo "  Status:     LOCKED  ($(luks_locked_reason))"
echo

if [ ! -t 0 ]; then
    echo "ERROR: no tty available for passphrase prompt." >&2
    echo "  For scripted use, pipe the passphrase to the helper directly:" >&2
    echo "    echo \"\$PASSPHRASE\" | $HELPER" >&2
    exit 1
fi

read -rsp "Passphrase: " PASSPHRASE
echo
if [ -z "$PASSPHRASE" ]; then
    echo "ERROR: empty passphrase. Aborting." >&2
    exit 1
fi

echo "Unlocking..."
echo

# Helper's stderr is human prose (let it flow to the user). Stdout is JSON;
# capture it so we can show a clean summary at the end without dumping raw
# JSON on the user.
HELPER_RC=0
HELPER_JSON=$(printf '%s' "$PASSPHRASE" | "$HELPER") || HELPER_RC=$?
unset PASSPHRASE

echo
case "$HELPER_RC" in
    0) echo "✓ /docker is unlocked and mounted." ;;
    1) echo "✗ Wrong passphrase or device error — nothing changed." ;;
    2) echo "✗ LUKS is not configured (per helper)." ;;
    3) echo "✗ Mount failed after unlock; mapper was closed back down." ;;
    4) echo "△ Unlocked + mounted, but a downstream service failed to start."
       echo "  Run 'systemctl status docker whp-boot-orchestrator' to investigate." ;;
    *) echo "✗ Helper exited with code $HELPER_RC (unexpected)." ;;
esac

# For diagnostics: the structured JSON is one line, easy to share if asked.
echo
echo "Helper JSON: $HELPER_JSON"

exit "$HELPER_RC"
