#!/bin/bash

# ProFTPD Helper Script for WHP (Web Hosting Panel)
# This script provides management tools for ProFTPD virtual users stored in MySQL

# 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 get MySQL connection details
get_mysql_config() {
    if [[ -f /root/.my.cnf ]]; then
        MYSQL_HOST=$(grep -E "^host=" /root/.my.cnf | cut -d'=' -f2)
        MYSQL_USER=$(grep -E "^user=" /root/.my.cnf | cut -d'=' -f2)
        MYSQL_PASSWORD=$(grep -E "^password=" /root/.my.cnf | cut -d'=' -f2)
        
        if [[ -z "$MYSQL_HOST" || -z "$MYSQL_USER" || -z "$MYSQL_PASSWORD" ]]; then
            print_status "ERROR" "MySQL configuration incomplete in /root/.my.cnf"
            exit 1
        fi
    else
        print_status "ERROR" "MySQL configuration file not found: /root/.my.cnf"
        exit 1
    fi
}

# Function to test MySQL connection
test_mysql_connection() {
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SELECT 1;" >/dev/null 2>&1
    if [[ $? -ne 0 ]]; then
        print_status "ERROR" "Cannot connect to MySQL database"
        exit 1
    fi
}

# Function to add FTP user
add_ftp_user() {
    local username=$1
    local password=$2
    
    if [[ -z "$username" ]]; then
        print_status "ERROR" "Username is required"
        return 1
    fi
    
    # Check if system user exists
    if ! id "$username" >/dev/null 2>&1; then
        print_status "ERROR" "System user $username does not exist"
        return 1
    fi
    
    # Get user information
    local uid=$(id -u "$username")
    local gid=$(id -g "$username")
    local homedir="/docker/users/$username"
    
    # Check if user already exists in FTP database
    local existing_user=$(mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -se "SELECT username FROM ftp_users WHERE username = '$username'")
    
    if [[ -n "$existing_user" ]]; then
        print_status "WARN" "FTP user $username already exists"
        return 0
    fi
    
    # If no password provided, prompt for it
    if [[ -z "$password" ]]; then
        echo -n "Enter password for $username: "
        read -s password
        echo
        if [[ -z "$password" ]]; then
            print_status "ERROR" "Password cannot be empty"
            return 1
        fi
    fi
    
    # Hash the password
    local password_hash=$(echo -n "$password" | php -r "echo password_hash(trim(fgets(STDIN)), PASSWORD_DEFAULT);")
    
    # Add user to database
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "
    INSERT INTO ftp_users (username, password, uid, gid, homedir, shell, created) 
    VALUES ('$username', '$password_hash', $uid, $gid, '$homedir', '/bin/false', NOW())
    ON DUPLICATE KEY UPDATE 
    password = VALUES(password), 
    uid = VALUES(uid), 
    gid = VALUES(gid), 
    homedir = VALUES(homedir),
    modified = NOW();"
    
    if [[ $? -eq 0 ]]; then
        # Set up default quota (1GB)
        local bytes_limit=$((1000 * 1024 * 1024))
        mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "
        INSERT INTO ftp_quotas (username, bytes_in_avail, bytes_out_avail, bytes_xfer_avail, files_in_avail, files_out_avail, files_xfer_avail) 
        VALUES ('$username', $bytes_limit, $bytes_limit, $((bytes_limit * 2)), 1000, 1000, 2000) 
        ON DUPLICATE KEY UPDATE 
        bytes_in_avail = VALUES(bytes_in_avail), 
        bytes_out_avail = VALUES(bytes_out_avail), 
        bytes_xfer_avail = VALUES(bytes_xfer_avail);"
        
        print_status "OK" "FTP user $username added successfully"
        return 0
    else
        print_status "ERROR" "Failed to add FTP user $username"
        return 1
    fi
}

# Function to remove FTP user
remove_ftp_user() {
    local username=$1
    
    if [[ -z "$username" ]]; then
        print_status "ERROR" "Username is required"
        return 1
    fi
    
    # Check if user exists in FTP database
    local existing_user=$(mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -se "SELECT username FROM ftp_users WHERE username = '$username'")
    
    if [[ -z "$existing_user" ]]; then
        print_status "WARN" "FTP user $username does not exist"
        return 0
    fi
    
    # Remove user from database
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "DELETE FROM ftp_users WHERE username = '$username';"
    
    if [[ $? -eq 0 ]]; then
        # Also remove quota record
        mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "DELETE FROM ftp_quotas WHERE username = '$username';"
        print_status "OK" "FTP user $username removed successfully"
        return 0
    else
        print_status "ERROR" "Failed to remove FTP user $username"
        return 1
    fi
}

# Function to list FTP users
list_ftp_users() {
    print_status "INFO" "FTP Users List"
    echo "============================================"
    
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "
    SELECT 
        u.username,
        u.uid,
        u.gid,
        u.homedir,
        u.count AS 'Login Count',
        COALESCE(u.accessed, 'Never') AS 'Last Access',
        u.created AS 'Created',
        CASE 
            WHEN q.bytes_in_avail IS NOT NULL THEN CONCAT(ROUND(q.bytes_in_avail / 1024 / 1024, 2), ' MB')
            ELSE 'No Quota'
        END AS 'Quota'
    FROM ftp_users u
    LEFT JOIN ftp_quotas q ON u.username = q.username
    ORDER BY u.username;" | column -t
}

# Function to show user details
show_user_details() {
    local username=$1
    
    if [[ -z "$username" ]]; then
        print_status "ERROR" "Username is required"
        return 1
    fi
    
    # Check if user exists
    local user_exists=$(mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -se "SELECT username FROM ftp_users WHERE username = '$username'")
    
    if [[ -z "$user_exists" ]]; then
        print_status "ERROR" "FTP user $username does not exist"
        return 1
    fi
    
    print_status "INFO" "FTP User Details: $username"
    echo "============================================"
    
    # Get user details
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "
    SELECT 
        'Username' AS 'Field', username AS 'Value' FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'UID', CAST(uid AS CHAR) FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'GID', CAST(gid AS CHAR) FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'Home Directory', homedir FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'Login Count', CAST(count AS CHAR) FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'Last Access', COALESCE(accessed, 'Never') FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'Created', created FROM ftp_users WHERE username = '$username'
    UNION ALL
    SELECT 'Modified', modified FROM ftp_users WHERE username = '$username';" | column -t
    
    echo ""
    print_status "INFO" "Quota Information"
    echo "============================================"
    
    # Get quota details
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "
    SELECT 
        CONCAT(ROUND(bytes_in_avail / 1024 / 1024, 2), ' MB') AS 'Upload Quota',
        CONCAT(ROUND(bytes_out_avail / 1024 / 1024, 2), ' MB') AS 'Download Quota',
        CONCAT(ROUND(bytes_xfer_avail / 1024 / 1024, 2), ' MB') AS 'Transfer Quota',
        files_in_avail AS 'Upload Files',
        files_out_avail AS 'Download Files',
        files_xfer_avail AS 'Transfer Files'
    FROM ftp_quotas WHERE username = '$username';" | column -t
}

# Function to update user quota
update_user_quota() {
    local username=$1
    local quota_mb=$2
    
    if [[ -z "$username" || -z "$quota_mb" ]]; then
        print_status "ERROR" "Username and quota (in MB) are required"
        return 1
    fi
    
    # Check if user exists
    local user_exists=$(mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -se "SELECT username FROM ftp_users WHERE username = '$username'")
    
    if [[ -z "$user_exists" ]]; then
        print_status "ERROR" "FTP user $username does not exist"
        return 1
    fi
    
    # Convert MB to bytes
    local bytes_limit=$((quota_mb * 1024 * 1024))
    
    # Update quota
    mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -D whp -e "
    INSERT INTO ftp_quotas (username, bytes_in_avail, bytes_out_avail, bytes_xfer_avail, files_in_avail, files_out_avail, files_xfer_avail) 
    VALUES ('$username', $bytes_limit, $bytes_limit, $((bytes_limit * 2)), 1000, 1000, 2000) 
    ON DUPLICATE KEY UPDATE 
    bytes_in_avail = VALUES(bytes_in_avail), 
    bytes_out_avail = VALUES(bytes_out_avail), 
    bytes_xfer_avail = VALUES(bytes_xfer_avail);"
    
    if [[ $? -eq 0 ]]; then
        print_status "OK" "Quota updated for user $username: ${quota_mb}MB"
        return 0
    else
        print_status "ERROR" "Failed to update quota for user $username"
        return 1
    fi
}

# Function to show ProFTPD status
show_proftpd_status() {
    print_status "INFO" "ProFTPD Service Status"
    echo "============================================"
    
    if systemctl is-active --quiet proftpd; then
        print_status "OK" "ProFTPD is running"
        echo "Process ID: $(systemctl show proftpd --property=MainPID --value)"
        echo "Start Time: $(systemctl show proftpd --property=ActiveEnterTimestamp --value)"
    else
        print_status "ERROR" "ProFTPD is not running"
    fi
    
    echo ""
    print_status "INFO" "Recent Connection Log"
    echo "============================================"
    
    if [[ -f /var/log/proftpd/access.log ]]; then
        tail -10 /var/log/proftpd/access.log
    else
        print_status "WARN" "Access log not found"
    fi
}

# Function to show help
show_help() {
    echo "ProFTPD Helper Script for WHP"
    echo "Usage: $0 <command> [options]"
    echo ""
    echo "Commands:"
    echo "  add <username> [password]    Add FTP user (prompts for password if not provided)"
    echo "  remove <username>            Remove FTP user"
    echo "  list                         List all FTP users"
    echo "  show <username>              Show detailed user information"
    echo "  quota <username> <mb>        Update user quota in MB"
    echo "  status                       Show ProFTPD service status"
    echo "  help                         Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 add testuser              # Add user with password prompt"
    echo "  $0 add testuser mypass123    # Add user with specified password"
    echo "  $0 remove testuser           # Remove user"
    echo "  $0 list                      # List all users"
    echo "  $0 show testuser             # Show user details"
    echo "  $0 quota testuser 2000       # Set 2GB quota for user"
    echo "  $0 status                    # Show service status"
}

# Main script logic
main() {
    check_root
    get_mysql_config
    test_mysql_connection
    
    case "${1:-}" in
        "add")
            add_ftp_user "$2" "$3"
            ;;
        "remove")
            remove_ftp_user "$2"
            ;;
        "list")
            list_ftp_users
            ;;
        "show")
            show_user_details "$2"
            ;;
        "quota")
            update_user_quota "$2" "$3"
            ;;
        "status")
            show_proftpd_status
            ;;
        "help"|"")
            show_help
            ;;
        *)
            print_status "ERROR" "Unknown command: $1"
            show_help
            exit 1
            ;;
    esac
}

# Run main function
main "$@" 