#!/usr/bin/env bash

# FTP Helper Script for WHP
# Manages FTP access for hosting users with chroot jailing

# 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 if user exists in system
user_exists() {
    local username=$1
    if id "$username" &>/dev/null; then
        return 0
    else
        return 1
    fi
}

# Function to check if user is a hosting user (UID >= 1000)
is_hosting_user() {
    local username=$1
    local uid=$(id -u "$username" 2>/dev/null)
    if [[ $uid -ge 1000 ]]; then
        return 0
    else
        return 1
    fi
}

# Function to ensure vsftpd required directories exist
ensure_vsftpd_dirs() {
    # Ensure secure chroot directory exists
    if [[ ! -d /var/run/vsftpd/empty ]]; then
        print_info "Creating missing vsftpd secure chroot directory..."
        mkdir -p /var/run/vsftpd/empty
        chmod 755 /var/run/vsftpd/empty
        print_status "Created /var/run/vsftpd/empty directory"
    fi
    
    # Ensure userlist file exists
    if [[ ! -f /etc/vsftpd.userlist ]]; then
        print_info "Creating missing vsftpd userlist file..."
        touch /etc/vsftpd.userlist
        chmod 600 /etc/vsftpd.userlist
        print_status "Created /etc/vsftpd.userlist file"
    fi
}

# Function to add user to FTP user list
add_ftp_user() {
    local username=$1
    
    # Ensure vsftpd directories exist first
    ensure_vsftpd_dirs
    
    # Check if user exists
    if ! user_exists "$username"; then
        print_error "User $username does not exist"
        return 1
    fi
    
    # Check if user is a hosting user
    if ! is_hosting_user "$username"; then
        print_error "User $username is not a hosting user (UID < 1000)"
        return 1
    fi
    
    # Check if user is already in FTP user list
    if grep -q "^$username$" /etc/vsftpd.userlist 2>/dev/null; then
        print_warning "User $username already has FTP access"
        return 0
    fi
    
    # Add user to FTP user list
    echo "$username" >> /etc/vsftpd.userlist
    print_status "Added $username to FTP user list"
    
    # Ensure user's home directory exists and has proper permissions
    local user_home="/docker/users/$username"
    if [[ ! -d "$user_home" ]]; then
        print_error "User home directory $user_home does not exist"
        return 1
    fi
    
    # Set proper permissions for FTP chroot
    chown "$username:$username" "$user_home"
    chmod 755 "$user_home"
    print_status "Set proper permissions for $user_home"
    
    # Create a simple welcome file if it doesn't exist
    local welcome_file="$user_home/README_FTP.txt"
    if [[ ! -f "$welcome_file" ]]; then
        cat > "$welcome_file" << EOF
Welcome to your FTP account!

This is your chrooted FTP directory. You can upload and manage files here.
Your web files should be placed in the appropriate domain directories.

For support, contact your hosting administrator.
EOF
        chown "$username:$username" "$welcome_file"
        chmod 644 "$welcome_file"
        print_status "Created welcome file for $username"
    fi
    
    # Reload vsftpd to pick up the new user
    reload_ftp
    
    return 0
}

# Function to remove user from FTP user list
remove_ftp_user() {
    local username=$1
    
    # Ensure vsftpd directories exist first
    ensure_vsftpd_dirs
    
    # Remove user from FTP user list
    if [[ -f /etc/vsftpd.userlist ]]; then
        sed -i "/^$username$/d" /etc/vsftpd.userlist
        print_status "Removed $username from FTP user list"
        
        # Reload vsftpd to pick up the removed user
        reload_ftp
    else
        print_warning "FTP user list does not exist"
    fi
    
    return 0
}

# Function to list FTP users
list_ftp_users() {
    if [[ -f /etc/vsftpd.userlist ]]; then
        print_info "Current FTP users:"
        while IFS= read -r line; do
            if [[ -n "$line" ]]; then
                echo "  - $line"
            fi
        done < /etc/vsftpd.userlist
    else
        print_warning "No FTP user list found"
    fi
}

# Function to check FTP service status
check_ftp_status() {
    # Check required directories first
    ensure_vsftpd_dirs
    
    if systemctl is-active --quiet vsftpd; then
        print_status "vsftpd service is running"
    else
        print_error "vsftpd service is not running"
    fi
    
    # Check if FTP port is listening
    if netstat -ln | grep -q ":21 "; then
        print_status "FTP port 21 is listening"
    else
        print_error "FTP port 21 is not listening"
    fi
    
    # Check required directories
    if [[ -d /var/run/vsftpd/empty ]]; then
        print_status "Secure chroot directory exists"
    else
        print_error "Secure chroot directory missing"
    fi
    
    if [[ -f /etc/vsftpd.userlist ]]; then
        print_status "User list file exists"
    else
        print_error "User list file missing"
    fi
}

# Function to reload FTP service (faster than restart)
reload_ftp() {
    # Try reload first (if supported), fallback to restart
    if systemctl reload vsftpd 2>/dev/null; then
        print_status "vsftpd service reloaded successfully"
        return 0
    else
        print_info "Reload not supported, restarting vsftpd service..."
        if systemctl restart vsftpd; then
            print_status "vsftpd service restarted successfully"
            return 0
        else
            print_error "Failed to restart vsftpd service"
            return 1
        fi
    fi
}

# Function to restart FTP service
restart_ftp() {
    print_info "Restarting vsftpd service..."
    if systemctl restart vsftpd; then
        print_status "vsftpd service restarted successfully"
    else
        print_error "Failed to restart vsftpd service"
        return 1
    fi
}

# Function to show help
show_help() {
    echo "FTP Helper Script for WHP"
    echo "Usage: $0 <command> [username]"
    echo ""
    echo "Commands:"
    echo "  add <username>     Add user to FTP access list (auto-reloads service)"
    echo "  remove <username>  Remove user from FTP access list (auto-reloads service)"
    echo "  list              List all FTP users"
    echo "  status            Check FTP service status"
    echo "  reload            Reload FTP service (faster than restart)"
    echo "  restart           Restart FTP service"
    echo "  help              Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 add johndoe"
    echo "  $0 remove johndoe"
    echo "  $0 list"
    echo "  $0 reload"
    echo "  $0 status"
}

# Main script logic
case "${1:-}" in
    "add")
        if [[ -z "${2:-}" ]]; then
            print_error "Username is required for add command"
            show_help
            exit 1
        fi
        add_ftp_user "$2"
        ;;
    "remove")
        if [[ -z "${2:-}" ]]; then
            print_error "Username is required for remove command"
            show_help
            exit 1
        fi
        remove_ftp_user "$2"
        ;;
    "list")
        list_ftp_users
        ;;
    "status")
        check_ftp_status
        ;;
    "reload")
        reload_ftp
        ;;
    "restart")
        restart_ftp
        ;;
    "help"|"")
        show_help
        ;;
    *)
        print_error "Unknown command: $1"
        show_help
        exit 1
        ;;
esac 