#!/usr/bin/env bash

# FTP Access Mode Toggle Script for WHP
# Switches between manual userlist mode and automatic access mode

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

# Function to check current mode
check_current_mode() {
    if [[ -f /etc/vsftpd/vsftpd.conf ]]; then
        # Check PAM configuration to determine mode
        if [[ -f /etc/pam.d/vsftpd ]]; then
            if grep -q "Simple PAM configuration for vsftpd automatic mode" /etc/pam.d/vsftpd; then
                echo "automatic"
            else
                echo "manual"
            fi
        else
            # Fall back to vsftpd.conf check
            if grep -q "userlist_enable=YES" /etc/vsftpd/vsftpd.conf; then
                echo "manual"
            else
                echo "unknown"
            fi
        fi
    else
        echo "not_configured"
    fi
}

# Function to set manual mode (userlist required)
set_manual_mode() {
    print_info "Switching to manual userlist mode..."
    
    # Copy manual configuration
    if [[ -f /root/whp/configs/vsftpd.conf ]]; then
        cp /root/whp/configs/vsftpd.conf /etc/vsftpd/vsftpd.conf
        print_status "Installed manual mode configuration"
    else
        print_error "Manual mode configuration not found!"
        return 1
    fi
    
    # Ensure userlist file exists
    if [[ ! -f /etc/vsftpd.userlist ]]; then
        touch /etc/vsftpd.userlist
        chmod 600 /etc/vsftpd.userlist
        print_status "Created empty userlist file"
    fi
    
    # Remove automatic mode PAM configuration and restore standard PAM
    if [[ -f /etc/pam.d/vsftpd ]]; then
        rm -f /etc/pam.d/vsftpd
        print_status "Removed automatic mode PAM configuration"
    fi
    
    # Update IP configuration
    update_ip_config
    
    # Restart vsftpd
    systemctl restart vsftpd
    print_status "Restarted vsftpd service"
    
    print_info "Manual mode activated. Users must be explicitly added to access FTP."
    print_info "Use: /root/whp/scripts/ftp-helper.sh add <username>"
}

# Function to set automatic mode (UID-based access)
set_automatic_mode() {
    print_info "Switching to automatic access mode..."
    
    # Copy automatic configuration
    if [[ -f /root/whp/configs/vsftpd-auto.conf ]]; then
        cp /root/whp/configs/vsftpd-auto.conf /etc/vsftpd/vsftpd.conf
        print_status "Installed automatic mode configuration"
    else
        print_error "Automatic mode configuration not found!"
        return 1
    fi
    
    # Install PAM configuration for automatic mode
    if [[ -f /root/whp/configs/vsftpd-auto.pam ]]; then
        cp /root/whp/configs/vsftpd-auto.pam /etc/pam.d/vsftpd
        chmod 644 /etc/pam.d/vsftpd
        print_status "Installed PAM configuration for automatic access"
    else
        print_error "PAM configuration not found!"
        return 1
    fi
    
    # Create and populate userlist with all hosting users (UID >= 1000)
    print_info "Creating automatic userlist with all hosting users..."
    /usr/bin/getent passwd | awk -F: '$3 >= 1000 && $3 != 65534 {print $1}' > /etc/vsftpd.userlist
    chmod 600 /etc/vsftpd.userlist
    user_count=$(wc -l < /etc/vsftpd.userlist)
    print_status "Added $user_count hosting users to FTP userlist"
    
    # Update IP configuration
    update_ip_config
    
    # Restart vsftpd
    systemctl restart vsftpd
    print_status "Restarted vsftpd service"
    
    print_info "Automatic mode activated. All hosting users (UID >= 1000) can access FTP."
    print_info "No manual user management required."
}

# Function to update IP configuration
update_ip_config() {
    # Get server IP using the same logic as setup.sh
    server_ip=""
    
    # Method 1: Try to get IP from main network interface
    server_ip=$(ip route get 8.8.8.8 | awk '{print $7}' | head -n1 2>/dev/null)
    
    # Method 2: If that fails, try hostname -I
    if [ -z "$server_ip" ] || [ "$server_ip" = "127.0.0.1" ]; then
        server_ip=$(hostname -I | awk '{print $1}' 2>/dev/null)
    fi
    
    # Method 3: If still no luck, try external IP detection
    if [ -z "$server_ip" ] || [[ "$server_ip" =~ ^192\.168\. ]] || [[ "$server_ip" =~ ^10\. ]] || [[ "$server_ip" =~ ^172\.(1[6-9]|2[0-9]|3[0-1])\. ]]; then
        server_ip=$(curl -s --connect-timeout 5 ifconfig.me 2>/dev/null)
    fi
    
    if [ -n "$server_ip" ]; then
        sed -i "s/\$PUBLIC_IP/$server_ip/g" /etc/vsftpd/vsftpd.conf
        print_status "Updated passive mode IP: $server_ip"
    else
        print_warning "Could not determine server IP - passive mode may need manual configuration"
    fi
}

# Function to show current status
show_status() {
    current_mode=$(check_current_mode)
    
    print_info "FTP Access Mode Status"
    echo "======================="
    
    case $current_mode in
        "manual")
            print_status "Current mode: Manual userlist mode"
            echo "  - Users must be explicitly added to /etc/vsftpd.userlist"
            echo "  - Use: /root/whp/scripts/ftp-helper.sh add <username>"
            if [[ -f /etc/vsftpd.userlist ]]; then
                user_count=$(wc -l < /etc/vsftpd.userlist)
                echo "  - Current FTP users: $user_count"
            fi
            ;;
        "automatic")
            print_status "Current mode: Automatic access mode"
            echo "  - All hosting users (UID >= 1000) automatically have FTP access"
            echo "  - Userlist is automatically managed"
            echo "  - New users automatically get FTP access when created"
            if [[ -f /etc/vsftpd.userlist ]]; then
                user_count=$(wc -l < /etc/vsftpd.userlist)
                echo "  - Current FTP users: $user_count"
            fi
            ;;
        "unknown")
            print_warning "Current mode: Unknown configuration"
            echo "  - vsftpd.conf exists but mode cannot be determined"
            ;;
        "not_configured")
            print_error "FTP not configured"
            echo "  - vsftpd.conf not found"
            ;;
    esac
    
    echo ""
    if systemctl is-active --quiet vsftpd; then
        print_status "vsftpd service is running"
    else
        print_error "vsftpd service is not running"
    fi
}

# Function to show help
show_help() {
    echo "FTP Access Mode Toggle Script for WHP"
    echo "Usage: $0 <command>"
    echo ""
    echo "Commands:"
    echo "  manual      Switch to manual userlist mode (users must be explicitly added)"
    echo "  automatic   Switch to automatic access mode (all hosting users can access)"
    echo "  status      Show current FTP access mode and status"
    echo "  help        Show this help message"
    echo ""
    echo "Modes:"
    echo "  Manual Mode:"
    echo "    - Users must be added to /etc/vsftpd.userlist to access FTP"
    echo "    - Use: /root/whp/scripts/ftp-helper.sh add <username>"
    echo "    - More secure, explicit control over FTP access"
    echo ""
    echo "  Automatic Mode:"
    echo "    - All hosting users (UID >= 1000) automatically have FTP access"
    echo "    - Userlist is automatically managed (no manual user addition required)"
    echo "    - New users automatically get FTP access when created"
    echo "    - More convenient, less administrative overhead"
    echo ""
    echo "Examples:"
    echo "  $0 automatic    # Enable automatic access for all hosting users"
    echo "  $0 manual       # Require explicit user addition to userlist"
    echo "  $0 status       # Check current mode"
}

# Main script logic
case "${1:-}" in
    "manual")
        set_manual_mode
        ;;
    "automatic")
        set_automatic_mode
        ;;
    "status")
        show_status
        ;;
    "help"|"")
        show_help
        ;;
    *)
        print_error "Unknown command: $1"
        show_help
        exit 1
        ;;
esac 