#!/bin/bash
# Setup script to allow passwordless sudo for WiFi control commands

echo "Setting up passwordless sudo for WiFi control..."
echo ""

# Create sudoers file for WiFi commands
SUDOERS_FILE="/etc/sudoers.d/kiwy-signage-wifi"

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "This script must be run as root (use sudo)"
    echo "Usage: sudo bash setup_wifi_control.sh"
    exit 1
fi

# Get the username who invoked sudo
ACTUAL_USER="${SUDO_USER:-$USER}"

echo "Configuring passwordless sudo for user: $ACTUAL_USER"
echo ""

# Create sudoers entry
cat > "$SUDOERS_FILE" << EOF
# Allow $ACTUAL_USER to control WiFi without password for Kiwy Signage Player
$ACTUAL_USER ALL=(ALL) NOPASSWD: /usr/sbin/rfkill block wifi
$ACTUAL_USER ALL=(ALL) NOPASSWD: /usr/sbin/rfkill unblock wifi
$ACTUAL_USER ALL=(ALL) NOPASSWD: /sbin/ifconfig wlan0 down
$ACTUAL_USER ALL=(ALL) NOPASSWD: /sbin/ifconfig wlan0 up
$ACTUAL_USER ALL=(ALL) NOPASSWD: /sbin/dhclient wlan0
EOF

# Set correct permissions
chmod 0440 "$SUDOERS_FILE"

echo "✓ Created sudoers file: $SUDOERS_FILE"
echo ""

# Validate the sudoers file
if visudo -c -f "$SUDOERS_FILE"; then
    echo "✓ Sudoers file validated successfully"
    echo ""
    echo "Setup complete! User '$ACTUAL_USER' can now control WiFi without password."
    echo ""
    echo "Test with:"
    echo "  sudo rfkill block wifi"
    echo "  sudo rfkill unblock wifi"
else
    echo "✗ Error: Sudoers file validation failed"
    echo "Removing invalid file..."
    rm -f "$SUDOERS_FILE"
    exit 1
fi
