#!/bin/sh
#
# lxtaz-ctrl-helper - the root half of lxtaz-ctrl, run via lxtaz-su
# (doas, no password for admins: see /etc/doas.conf) or `tazbox su`.
# Plain word arguments only: tazbox su flattens its argv into one
# `su -c` string, and a doas `cmd` rule must stay easy to audit.
#
# Usage: lxtaz-ctrl-helper wifi on|off IFACE
#        lxtaz-ctrl-helper bt on|off
#
# Copyright (C) 2026 SliTaz GNU/Linux - BSD License
# Author: Christophe Lincoln <pankso@slitaz.org>
# AI assistant: Claude (Anthropic)
#

usage() {
	echo "Usage: $(basename $0) wifi on|off IFACE | bt on|off" >&2
	exit 1
}

[ "$(id -u)" -eq 0 ] || { echo "$(basename $0): must be root" >&2; exit 1; }

case "$1 $2" in
	'wifi on'|'wifi off')
		# Interface name from /sys/class/net, never a path or option
		[ -n "$3" ] && [ -d "/sys/class/net/$3" ] || usage
		case "$3" in */*|-*) usage ;; esac
		if [ "$2" = 'on' ]; then
			sed -i 's/^WIFI=.*/WIFI="yes"/' /etc/network.conf
			ifconfig "$3" up
			/etc/init.d/network.sh start 2>/dev/null
		else
			/etc/init.d/network.sh stop 2>/dev/null
			ifconfig "$3" down
			sed -i 's/^WIFI=.*/WIFI="no"/' /etc/network.conf
		fi ;;
	'bt on'|'bt off')
		trame bluetooth power "$2" ;;
	*)
		usage ;;
esac
