#!/bin/bash
# LibrePortal docker-socket permission helper — the only root-privileged chmod of
# the docker sockets the manager may trigger (the type switcher hides/exposes the
# inactive/active mode's socket). Installed root:root 0755 to /usr/local/lib/libreportal/ by
# init.sh. Self-contained; the socket paths are computed here (never caller-
# supplied), so the scoped sudoers can allow it instead of blanket `sudo chmod`.
#
# Exit: 0 = socket found + chmod'd, 3 = socket absent (caller treats as not-found).

set -u

[[ $EUID -eq 0 ]] || { echo "libreportal-socket: must run as root" >&2; exit 1; }

# SYSTEM_DIR baked at install; unbaked copies keep the "__" sentinel.
SYSTEM_DIR="__SYSTEM_DIR__"
[[ "$SYSTEM_DIR" == *"__"* || -z "$SYSTEM_DIR" ]] && SYSTEM_DIR="/libreportal-system"
DB_CFG="$SYSTEM_DIR/configs/general/general_docker_install"
ROOTED_SOCK="/var/run/docker.sock"

_rootless_sock() {
    local u uid
    u=$(grep -h '^CFG_DOCKER_INSTALL_USER=' "$DB_CFG" 2>/dev/null | head -1 | cut -d= -f2 | awk '{print $1}')
    [[ -n "$u" ]] || return 1
    uid=$(id -u "$u" 2>/dev/null) || return 1
    printf '/run/user/%s/docker.sock' "$uid"
}

which="${1:-}"; state="${2:-}"
case "$which" in
    rootless) sock="$(_rootless_sock)" || exit 3 ;;
    rooted)   sock="$ROOTED_SOCK" ;;
    *) echo "usage: libreportal-socket {rootless|rooted} {on|off}" >&2; exit 2 ;;
esac

[[ -e "$sock" ]] || exit 3

case "$state" in
    on)  chmod +r  "$sock" ;;
    off) chmod o-r "$sock" ;;
    *) echo "usage: libreportal-socket {rootless|rooted} {on|off}" >&2; exit 2 ;;
esac
