#!/bin/bash

# Quota Helper Script for WHP
# This script provides easy access to quota management functions

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

# Ensure running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Error: This script must be run as root${NC}"
    exit 1
fi

# Function to get filesystem information from quota script
get_filesystem_info() {
    /root/whp/scripts/setup-quotas.sh status 2>/dev/null | grep -E "^(Filesystem|Mount point|Users directory):" | cut -d: -f2 | xargs
}

# Function to get mount point for quota operations
get_mount_point() {
    local info=($(get_filesystem_info))
    if [ ${#info[@]} -ge 2 ]; then
        echo "${info[1]}"
    else
        echo "/"
    fi
}

# Function to show usage
show_usage() {
    echo -e "${BLUE}WHP Quota Helper Script${NC}"
    echo ""
    echo "Usage: $0 [COMMAND] [OPTIONS]"
    echo ""
    echo "Commands:"
    echo "  setup                    - Initial quota setup"
    echo "  sync                     - Sync all user quotas with database"
    echo "  status                   - Show quota status for all users"
    echo "  user <username>          - Show quota for specific user"
    echo "  set <username> <limit>   - Set quota for user (MB)"
    echo "  remove <username>        - Remove quota for user"
    echo "  check                    - Check if quotas are enabled"
    echo "  enable                   - Enable quotas on filesystem"
    echo "  report                   - Generate quota usage report"
    echo "  info                     - Show filesystem information"
    echo ""
    echo "Examples:"
    echo "  $0 setup"
    echo "  $0 sync"
    echo "  $0 user john"
    echo "  $0 set john 2000"
    echo "  $0 status"
    echo "  $0 info"
}

# Function to check quota status
check_quotas() {
    echo -e "${BLUE}Checking quota status...${NC}"
    
    # Check if quota tools are installed
    if ! command -v quotacheck &> /dev/null; then
        echo -e "${RED}✗ Quota tools not installed${NC}"
        return 1
    fi
    
    echo -e "${GREEN}✓ Quota tools installed${NC}"
    
    # Get the mount point dynamically
    local mount_point=$(get_mount_point)
    echo -e "${BLUE}Checking quotas on: $mount_point${NC}"
    
    # Check if quotas are enabled
    if quotaon -p "$mount_point" 2>/dev/null | grep -q "user quota on"; then
        echo -e "${GREEN}✓ User quotas enabled on $mount_point${NC}"
    else
        echo -e "${YELLOW}⚠ User quotas not enabled on $mount_point${NC}"
        return 1
    fi
    
    return 0
}

# Function to show quota report
quota_report() {
    echo -e "${BLUE}WHP User Quota Report${NC}"
    echo -e "${BLUE}=====================${NC}"
    echo ""
    
    if ! check_quotas >/dev/null 2>&1; then
        echo -e "${RED}Quotas are not properly enabled${NC}"
        return 1
    fi
    
    echo -e "${YELLOW}Username${NC}\t${YELLOW}Used (MB)${NC}\t${YELLOW}Limit (MB)${NC}\t${YELLOW}Usage %${NC}\t${YELLOW}Status${NC}"
    echo "----------------------------------------------------------------"
    
    # Get list of users with UID >= 1000 (hosting users)
    while IFS=: read -r username _ uid _ _ home _; do
        if [ "$uid" -ge 1000 ] && [ "$username" != "nobody" ]; then
            # Get quota info
            quota_output=$(quota -u "$username" 2>/dev/null | tail -n 1)
            if [ -n "$quota_output" ]; then
                used_kb=$(echo "$quota_output" | awk '{print $2}')
                limit_kb=$(echo "$quota_output" | awk '{print $3}')
                
                if [ "$limit_kb" -gt 0 ]; then
                    used_mb=$((used_kb / 1024))
                    limit_mb=$((limit_kb / 1024))
                    usage_percent=$(( (used_kb * 100) / limit_kb ))
                    
                    # Determine status color
                    if [ "$usage_percent" -gt 80 ]; then
                        status="${RED}HIGH${NC}"
                    elif [ "$usage_percent" -gt 60 ]; then
                        status="${YELLOW}WARN${NC}"
                    else
                        status="${GREEN}OK${NC}"
                    fi
                    
                    printf "%-12s\t%-10s\t%-11s\t%-8s\t%s\n" \
                        "$username" "${used_mb}" "${limit_mb}" "${usage_percent}%" "$status"
                fi
            fi
        fi
    done < /etc/passwd
}

# Function to show user quota
show_user_quota() {
    local username="$1"
    
    if [ -z "$username" ]; then
        echo -e "${RED}Error: Username required${NC}"
        return 1
    fi
    
    if ! id "$username" &>/dev/null; then
        echo -e "${RED}Error: User '$username' does not exist${NC}"
        return 1
    fi
    
    echo -e "${BLUE}Quota information for user: $username${NC}"
    echo "----------------------------------------"
    
    quota_output=$(quota -u "$username" 2>/dev/null)
    if [ -n "$quota_output" ]; then
        echo "$quota_output"
    else
        echo -e "${YELLOW}No quota information available${NC}"
    fi
}

# Function to show filesystem information
show_filesystem_info() {
    echo -e "${BLUE}Filesystem Information${NC}"
    echo -e "${BLUE}======================${NC}"
    echo ""
    
    /root/whp/scripts/setup-quotas.sh status
}

# Main script logic
case "$1" in
    setup)
        echo -e "${BLUE}Setting up user quotas...${NC}"
        /root/whp/scripts/setup-quotas.sh setup
        ;;
    sync)
        echo -e "${BLUE}Syncing user quotas...${NC}"
        /root/whp/scripts/setup-quotas.sh sync
        ;;
    status)
        echo -e "${BLUE}Current quota status:${NC}"
        mount_point=$(get_mount_point)
        echo "Mount point: $mount_point"
        echo ""
        repquota -u "$mount_point" 2>/dev/null || echo -e "${RED}Quotas not active or not supported${NC}"
        ;;
    user)
        show_user_quota "$2"
        ;;
    set)
        if [ -z "$2" ] || [ -z "$3" ]; then
            echo -e "${RED}Error: Usage: $0 set <username> <limit_mb>${NC}"
            exit 1
        fi
        echo -e "${BLUE}Setting quota for $2 to $3 MB...${NC}"
        /root/whp/scripts/setup-quotas.sh user "$2" "$3"
        ;;
    remove)
        if [ -z "$2" ]; then
            echo -e "${RED}Error: Username required${NC}"
            exit 1
        fi
        echo -e "${BLUE}Removing quota for $2...${NC}"
        /root/whp/scripts/setup-quotas.sh remove "$2"
        ;;
    check)
        check_quotas
        ;;
    enable)
        echo -e "${BLUE}Enabling quotas...${NC}"
        mount_point=$(get_mount_point)
        echo "Target mount point: $mount_point"
        quotacheck -cum "$mount_point" 2>/dev/null
        quotaon "$mount_point" 2>/dev/null
        echo -e "${GREEN}✓ Quota enable command executed on $mount_point${NC}"
        ;;
    report)
        quota_report
        ;;
    info)
        show_filesystem_info
        ;;
    *)
        show_usage
        exit 1
        ;;
esac

exit 0 