#!/usr/bin/env bash
# Lock the sudo password file: owner-read-only and immutable.
#
# Takes no path argument on purpose. secret-file-gate denies any tool call that
# names the file, so the only way to act on it is a command that does not — the
# path is resolved here, and this script can only lock, never read or remove.
#
# usage: deck-secret-lock [--status]
set -euo pipefail

PASSFILE="${DECK_SUDO_PASSFILE:-$HOME/stupid.user}"
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

die() { echo "deck-secret-lock: ERROR: $*" >&2; exit 1; }

[[ -f "$PASSFILE" ]] || die "no password file at $PASSFILE — nothing to lock"

if [[ "${1:-}" == "--status" ]]; then
  stat -c 'mode=%a owner=%U' "$PASSFILE"
  if lsattr -l "$PASSFILE" 2>/dev/null | grep -q Immutable; then
    echo "immutable=yes"
  else
    echo "immutable=no"
    exit 1
  fi
  exit 0
fi

chmod 400 "$PASSFILE"
"$SELF_DIR/deck-sudo" chattr +i "$PASSFILE" || die "could not set the immutable flag"

echo "locked: $(stat -c 'mode=%a' "$PASSFILE"), immutable"
