#!/bin/bash

# Script to configure sudo permissions for backup operations
# Usage: sudo bash fix-backup-sudo.sh

echo "=== Configuring Sudo Permissions for Backup ==="

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

# Check if www-data-sudoers file exists
if [ ! -f "www-data-sudoers" ]; then
    echo "Error: www-data-sudoers file not found in current directory"
    exit 1
fi

# Validate sudoers file syntax
echo "Validating sudoers syntax..."
if ! visudo -c -f www-data-sudoers; then
    echo "Error: Invalid sudoers syntax in www-data-sudoers file"
    exit 1
fi

echo "Syntax OK"

# Copy sudoers file
echo "Installing sudoers configuration..."
cp www-data-sudoers /etc/sudoers.d/www-data-backup

# Set correct permissions (must be 0444 or 0440)
chmod 0440 /etc/sudoers.d/www-data-backup

# Verify installation
echo "Verifying installation..."
if [ -f "/etc/sudoers.d/www-data-backup" ]; then
    echo "Sudoers file installed: /etc/sudoers.d/www-data-backup"
    ls -la /etc/sudoers.d/www-data-backup
else
    echo "Error: Failed to install sudoers file"
    exit 1
fi

# Validate entire sudoers configuration
echo "Validating entire sudoers configuration..."
if visudo -c; then
    echo "All sudoers configurations are valid"
else
    echo "Error: Sudoers configuration validation failed"
    exit 1
fi

# Test sudo access for www-data user
echo "Testing sudo access for www-data user..."
if sudo -u www-data sudo -n /bin/tar --version > /dev/null 2>&1; then
    echo "SUCCESS: www-data can run 'sudo tar' without password"
else
    echo "WARNING: Test failed - www-data may not be able to run sudo commands"
    echo "You may need to restart your web server or log out and back in"
fi

echo ""
echo "=== Done! ==="
echo "Backup sudo permissions have been configured."
echo "www-data can now run the following commands without password:"
echo "  - /bin/tar"
echo "  - /bin/cp"
echo "  - /usr/bin/mysqldump"
echo ""
echo "Note: If backup still fails, please:"
echo "  1. Restart your web server (apache2/nginx + php-fpm)"
echo "  2. Or log out and log back in to the server"
