#!/bin/bash

# Fix FTP Chroot Permissions Script for WHP
# This script fixes directory permissions for existing users to work with ProFTPD chroot

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

# Function to print colored output
print_status() {
    local status=$1
    local message=$2
    case $status in
        "OK")
            echo -e "${GREEN}✓${NC} $message"
            ;;
        "WARN")
            echo -e "${YELLOW}⚠${NC} $message"
            ;;
        "ERROR")
            echo -e "${RED}✗${NC} $message"
            ;;
        "INFO")
            echo -e "${BLUE}ℹ${NC} $message"
            ;;
    esac
}

# Function to check if running as root
check_root() {
    if [[ $EUID -ne 0 ]]; then
        print_status "ERROR" "This script must be run as root"
        exit 1
    fi
}

# Function to fix permissions for a single user
fix_user_permissions() {
    local username=$1
    local user_dir="/docker/users/$username"
    
    if [[ ! -d "$user_dir" ]]; then
        print_status "WARN" "Directory does not exist: $user_dir"
        return 1
    fi
    
    # Check if user exists
    if ! id "$username" >/dev/null 2>&1; then
        print_status "WARN" "System user does not exist: $username"
        return 1
    fi
    
    print_status "INFO" "Fixing permissions for user: $username"
    
    # Set proper ownership for user home directory
    chown "$username:$username" "$user_dir"
    chmod 755 "$user_dir"
    
    # Fix permissions for any existing domain directories
    local domain_dirs=($(find "$user_dir" -maxdepth 1 -type d ! -name ".*" ! -path "$user_dir"))
    
    if [[ ${#domain_dirs[@]} -gt 0 ]]; then
        print_status "INFO" "Found domain directories for $username:"
        for domain_dir in "${domain_dirs[@]}"; do
            local domain_name=$(basename "$domain_dir")
            print_status "INFO" "  - $domain_name"
            
            # Set proper ownership for domain directory
            chown -R "$username:$username" "$domain_dir"
            chmod -R 755 "$domain_dir"
        done
    else
        print_status "INFO" "No domain directories found for $username"
    fi
    
    print_status "OK" "Fixed permissions for $username"
    
    # Show the directory structure
    echo "  Directory structure:"
    echo "  $user_dir ($username:$username 755)"
    if [[ ${#domain_dirs[@]} -gt 0 ]]; then
        for domain_dir in "${domain_dirs[@]}"; do
            local domain_name=$(basename "$domain_dir")
            echo "  ├── $domain_name/ ($username:$username 755)"
        done
    else
        echo "  (No domain directories yet - created when domains are added)"
    fi
    
    return 0
}

# Function to fix all hosting users
fix_all_users() {
    print_status "INFO" "Finding all hosting users (UID >= 1000)..."
    
    local users_fixed=0
    local users_failed=0
    
    # Get all hosting users (UID >= 1000, excluding nobody)
    while IFS=: read -r username _ uid gid _ home shell; do
        if [[ $uid -ge 1000 && $uid -ne 65534 ]]; then
            echo ""
            if fix_user_permissions "$username"; then
                ((users_fixed++))
            else
                ((users_failed++))
            fi
        fi
    done < /etc/passwd
    
    echo ""
    print_status "INFO" "Summary:"
    echo "  Users fixed: $users_fixed"
    echo "  Users failed: $users_failed"
}

# Function to show current permissions for a user
show_user_permissions() {
    local username=$1
    local user_dir="/docker/users/$username"
    
    if [[ ! -d "$user_dir" ]]; then
        print_status "ERROR" "Directory does not exist: $user_dir"
        return 1
    fi
    
    print_status "INFO" "Current permissions for $username:"
    
    echo "Directory structure and permissions:"
    ls -la "$user_dir/.."  | grep "$(basename "$user_dir")"
    
    # Show domain directory permissions
    local domain_dirs=($(find "$user_dir" -maxdepth 1 -type d ! -name ".*" ! -path "$user_dir"))
    
    if [[ ${#domain_dirs[@]} -gt 0 ]]; then
        echo "  Domain directories:"
        for domain_dir in "${domain_dirs[@]}"; do
            local domain_name=$(basename "$domain_dir")
            ls -la "$user_dir" | grep "$domain_name"
        done
    else
        echo "  No domain directories found (created when domains are added)"
    fi
}

# Function to test FTP connection for a user
test_ftp_connection() {
    local username=$1
    
    if [[ -z "$username" ]]; then
        print_status "ERROR" "Username is required for FTP test"
        return 1
    fi
    
    print_status "INFO" "Testing FTP connection for $username..."
    
    # Check if user exists in FTP database
    local mysql_config="/root/.my.cnf"
    if [[ ! -f "$mysql_config" ]]; then
        print_status "ERROR" "MySQL configuration not found"
        return 1
    fi
    
    local mysql_password=$(grep -E "^password=" "$mysql_config" | cut -d'=' -f2)
    local ftp_user_exists=$(mysql -h localhost -u root -p"$mysql_password" -D whp -se "SELECT username FROM ftp_users WHERE username = '$username'")
    
    if [[ -n "$ftp_user_exists" ]]; then
        print_status "OK" "User exists in FTP database"
    else
        print_status "ERROR" "User does not exist in FTP database"
        return 1
    fi
    
    # Check ProFTPD status
    if systemctl is-active --quiet proftpd; then
        print_status "OK" "ProFTPD service is running"
    else
        print_status "ERROR" "ProFTPD service is not running"
        return 1
    fi
    
    print_status "INFO" "Manual FTP test suggested:"
    echo "  ftp localhost"
    echo "  Username: $username"
    echo "  Expected chroot: /docker/users/$username"
    echo "  Working directory: $username home (domain directories created when domains are added)"
}

# Function to show help
show_help() {
    echo "FTP Permissions Fix Script for WHP"
    echo "Usage: $0 <command> [options]"
    echo ""
    echo "Commands:"
    echo "  fix <username>       Fix permissions for specific user"
    echo "  fix-all              Fix permissions for all hosting users"
    echo "  show <username>      Show current permissions for user"
    echo "  test <username>      Test FTP setup for user"
    echo "  help                 Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 fix testuser      # Fix permissions for testuser"
    echo "  $0 fix-all           # Fix all hosting users"
    echo "  $0 show testuser     # Show current permissions"
    echo "  $0 test testuser     # Test FTP setup"
}

# Main script logic
main() {
    check_root
    
    case "${1:-}" in
        "fix")
            if [[ -z "$2" ]]; then
                print_status "ERROR" "Username is required"
                show_help
                exit 1
            fi
            fix_user_permissions "$2"
            ;;
        "fix-all")
            fix_all_users
            ;;
        "show")
            if [[ -z "$2" ]]; then
                print_status "ERROR" "Username is required"
                show_help
                exit 1
            fi
            show_user_permissions "$2"
            ;;
        "test")
            if [[ -z "$2" ]]; then
                print_status "ERROR" "Username is required"
                show_help
                exit 1
            fi
            test_ftp_connection "$2"
            ;;
        "help"|"")
            show_help
            ;;
        *)
            print_status "ERROR" "Unknown command: $1"
            show_help
            exit 1
            ;;
    esac
}

# Run main function
main "$@" 