#!/bin/bash
# Manage admin users for Post-ERG nginx basic authentication

set -e

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

PASSWORD_FILE="/etc/nginx/.htpasswd-posterg"

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

# Check if htpasswd is available
if ! command -v htpasswd &> /dev/null; then
    echo -e "${YELLOW}Installing apache2-utils...${NC}"
    apt-get update -qq
    apt-get install -y apache2-utils
fi

show_menu() {
    echo ""
    echo -e "${BLUE}════════════════════════════════════════${NC}"
    echo -e "${BLUE}  Post-ERG Admin User Management${NC}"
    echo -e "${BLUE}════════════════════════════════════════${NC}"
    echo ""
    echo "1. List all users"
    echo "2. Add new user"
    echo "3. Change user password"
    echo "4. Delete user"
    echo "5. Reset all (create new password file)"
    echo "6. Exit"
    echo ""
    echo -n "Choose an option [1-6]: "
}

list_users() {
    echo ""
    if [ ! -f "$PASSWORD_FILE" ]; then
        echo -e "${YELLOW}No password file found.${NC}"
        return
    fi
    
    echo -e "${GREEN}Current admin users:${NC}"
    echo "────────────────────────"
    cut -d: -f1 "$PASSWORD_FILE" | nl
    echo ""
}

add_user() {
    echo ""
    echo -n "Enter new username: "
    read -r USERNAME
    
    if [ -z "$USERNAME" ]; then
        echo -e "${RED}Username cannot be empty${NC}"
        return
    fi
    
    # Check if user already exists
    if [ -f "$PASSWORD_FILE" ] && grep -q "^${USERNAME}:" "$PASSWORD_FILE"; then
        echo -e "${YELLOW}User '$USERNAME' already exists. Use option 3 to change password.${NC}"
        return
    fi
    
    # Add user (use -c only if file doesn't exist)
    if [ ! -f "$PASSWORD_FILE" ]; then
        htpasswd -c "$PASSWORD_FILE" "$USERNAME"
    else
        htpasswd "$PASSWORD_FILE" "$USERNAME"
    fi
    
    echo -e "${GREEN}✓ User '$USERNAME' added successfully${NC}"
}

change_password() {
    list_users
    echo -n "Enter username to change password: "
    read -r USERNAME
    
    if [ -z "$USERNAME" ]; then
        echo -e "${RED}Username cannot be empty${NC}"
        return
    fi
    
    if [ ! -f "$PASSWORD_FILE" ]; then
        echo -e "${RED}Password file not found${NC}"
        return
    fi
    
    if ! grep -q "^${USERNAME}:" "$PASSWORD_FILE"; then
        echo -e "${RED}User '$USERNAME' not found${NC}"
        return
    fi
    
    htpasswd "$PASSWORD_FILE" "$USERNAME"
    echo -e "${GREEN}✓ Password changed for user '$USERNAME'${NC}"
}

delete_user() {
    list_users
    echo -n "Enter username to delete: "
    read -r USERNAME
    
    if [ -z "$USERNAME" ]; then
        echo -e "${RED}Username cannot be empty${NC}"
        return
    fi
    
    if [ ! -f "$PASSWORD_FILE" ]; then
        echo -e "${RED}Password file not found${NC}"
        return
    fi
    
    if ! grep -q "^${USERNAME}:" "$PASSWORD_FILE"; then
        echo -e "${RED}User '$USERNAME' not found${NC}"
        return
    fi
    
    echo -n "Are you sure you want to delete user '$USERNAME'? [y/N] "
    read -r CONFIRM
    
    if [ "$CONFIRM" = "y" ] || [ "$CONFIRM" = "Y" ]; then
        htpasswd -D "$PASSWORD_FILE" "$USERNAME"
        echo -e "${GREEN}✓ User '$USERNAME' deleted${NC}"
    else
        echo "Cancelled"
    fi
}

reset_all() {
    echo ""
    echo -e "${YELLOW}WARNING: This will delete ALL existing users!${NC}"
    echo -n "Are you sure? [y/N] "
    read -r CONFIRM
    
    if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
        echo "Cancelled"
        return
    fi
    
    # Backup existing file
    if [ -f "$PASSWORD_FILE" ]; then
        BACKUP="${PASSWORD_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
        cp "$PASSWORD_FILE" "$BACKUP"
        echo -e "${GREEN}✓ Backed up to: $BACKUP${NC}"
    fi
    
    echo ""
    echo -n "Enter new username: "
    read -r USERNAME
    
    if [ -z "$USERNAME" ]; then
        echo -e "${RED}Username cannot be empty${NC}"
        return
    fi
    
    htpasswd -c "$PASSWORD_FILE" "$USERNAME"
    echo -e "${GREEN}✓ Password file reset with user '$USERNAME'${NC}"
}

# Main loop
while true; do
    show_menu
    read -r CHOICE
    
    case $CHOICE in
        1)
            list_users
            ;;
        2)
            add_user
            ;;
        3)
            change_password
            ;;
        4)
            delete_user
            ;;
        5)
            reset_all
            ;;
        6)
            echo ""
            echo "Goodbye!"
            exit 0
            ;;
        *)
            echo -e "${RED}Invalid option${NC}"
            ;;
    esac
done
