#!/bin/bash

# PW Control Panel - Sudo Configuration Setup Script
# This script enables passwordless sudo for the web server user

echo "====================================="
echo "PW Control Panel Sudo Setup"
echo "====================================="
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Error: Please run as root"
    echo "   Usage: sudo $0"
    exit 1
fi

# Configuration
SUDOERS_FILE="/etc/sudoers.d/pw-cp"
WEB_USER="www-data"
CONTROL_SCRIPT="/var/www/html/cp/resources/scripts/pw_control.sh"

echo "📝 Creating sudoers configuration..."
echo "   File: $SUDOERS_FILE"
echo "   User: $WEB_USER"
echo ""

# Create sudoers configuration
cat > "$SUDOERS_FILE" << 'EOSUDO'
# PW Control Panel - Passwordless Sudo Configuration
# Allows web server user to run server control scripts

# Allow www-data to run PW control script with passwordless sudo
www-data ALL=(ALL) NOPASSWD: /var/www/html/cp/resources/scripts/pw_control.sh

# Allow www-data to use pkill for stopping game server processes
www-data ALL=(ALL) NOPASSWD: /usr/bin/pkill, /bin/kill, /usr/bin/kill

# Allow www-data to execute bash scripts
www-data ALL=(ALL) NOPASSWD: /bin/bash
EOSUDO

echo "✅ Sudoers file created"

# Set correct permissions (0440 is required for sudoers files)
chmod 0440 "$SUDOERS_FILE"
echo "✅ Permissions set to 0440"

# Verify sudoers syntax
echo ""
echo "🔍 Verifying sudoers syntax..."
if visudo -c 2>&1 | grep -q "$SUDOERS_FILE: parsed OK"; then
    echo "✅ Syntax is valid"
else
    echo "❌ Syntax error detected!"
    visudo -c
    exit 1
fi

# Test passwordless sudo
echo ""
echo "🧪 Testing passwordless sudo..."
TEST_OUTPUT=$(sudo -u $WEB_USER sudo -n /var/www/html/cp/resources/scripts/pw_control.sh 2>&1)
TEST_EXIT_CODE=$?

if [ $TEST_EXIT_CODE -eq 0 ] || echo "$TEST_OUTPUT" | grep -q "Usage:"; then
    echo "✅ Passwordless sudo is working!"
else
    echo "❌ Passwordless sudo test failed!"
    echo "   Output: $TEST_OUTPUT"
    echo "   Exit code: $TEST_EXIT_CODE"
fi

# Show current configuration
echo ""
echo "📋 Current configuration:"
cat "$SUDOERS_FILE"

echo ""
echo "====================================="
echo "✨ Setup completed successfully!"
echo "====================================="
echo ""
echo "The web server ($WEB_USER) can now execute:"
echo "  • PW control scripts without password"
echo "  • pkill/kill commands without password"
echo ""
