#!/usr/bin/sh
# SPDX-License-Identifier: GPL-2.0-or-later
#
# /usr/libexec/pocketds-fancontrol-set-profile <profile>
#
# Privileged setter for the fan-control profile. Validates the
# argument against a closed allowlist, then writes /etc/pocketds-
# fancontrol/profile atomically. Invoked via pkexec from the
# AppIndicator (see org.pocketds.fancontrol.policy).
#
# We do this in a tiny shell helper rather than letting pkexec call
# `tee` or `cp` so the only thing the user is being prompted to allow
# is "set fan profile" -- not "run arbitrary file writes as root".

set -eu

PROFILE_DIR="/etc/pocketds-fancontrol"
PROFILE_FILE="${PROFILE_DIR}/profile"

if [ "$#" -ne 1 ]; then
    echo "usage: $0 <auto|quiet|moderate|aggressive|custom|off>" >&2
    exit 2
fi

case "$1" in
    auto|quiet|moderate|aggressive|custom|off) ;;
    *)
        echo "invalid profile: $1" >&2
        exit 2
        ;;
esac

mkdir -p "${PROFILE_DIR}"
tmp="$(mktemp "${PROFILE_FILE}.XXXXXX")"
printf '%s\n' "$1" > "${tmp}"
chmod 0644 "${tmp}"
mv -f "${tmp}" "${PROFILE_FILE}"
