#!/bin/sh
# wlanpi-core-preflight: ExecStartPre probe; exits non-zero unless the secrets state directory is writable

set -eu

# Keep in sync with wlanpi_core.constants.SECRETS_DIR
WLANPI_HOME="/home/wlanpi"
STATE_DIR="$WLANPI_HOME/.local/share/wlanpi-core/secrets"

fail() {
    echo "wlanpi-core-preflight: FATAL: $1" >&2
    exit 1
}

# Run as root, mkdir -p below would leave the wlanpi user's XDG data home root-owned.
for d in "$WLANPI_HOME/.local" "$WLANPI_HOME/.local/share"; do
    if [ ! -d "$d" ]; then
        mkdir -m 0755 "$d" 2>/dev/null || fail "cannot create $d"
        chown wlanpi:wlanpi "$d" 2>/dev/null || fail "cannot chown $d to wlanpi:wlanpi"
    elif [ "$(stat -c %U:%G "$d" 2>/dev/null)" != "wlanpi:wlanpi" ]; then
        chown wlanpi:wlanpi "$d" 2>/dev/null || fail "cannot chown $d to wlanpi:wlanpi"
    fi
done

# shellcheck disable=SC2174  # only the leaf needs 0700
mkdir -p -m 0700 "$STATE_DIR" 2>/dev/null || fail "cannot create state directory $STATE_DIR"

[ -d "$STATE_DIR" ] || fail "state directory $STATE_DIR does not exist"

PROBE="$STATE_DIR/.preflight_$$"
if ! ( : > "$PROBE" ) 2>/dev/null; then
    fail "state directory $STATE_DIR is not writable"
fi
rm -f "$PROBE" 2>/dev/null || true

echo "wlanpi-core-preflight: state directory $STATE_DIR is writable"
exit 0
