#!/bin/bash

# WHP API Authentication Helper Script
# This script helps authenticate and interact with the WHP User Management API

SERVER_URL="http://192.168.1.105:8080"
COOKIE_FILE="whp_cookies.txt"

# 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() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_header() {
    echo -e "${BLUE}[API]${NC} $1"
}

# Function to authenticate
authenticate() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        print_error "Usage: $0 auth <username> <password>"
        exit 1
    fi
    
    print_status "Authenticating as $1..."
    
    # Attempt to login and save cookies
    response=$(curl -s -c $COOKIE_FILE -X POST \
        -d "user=$1&password=$2" \
        "$SERVER_URL/login.php")
    
    # Check if login was successful
    if grep -q "nonce" $COOKIE_FILE 2>/dev/null; then
        print_status "Authentication successful! Cookies saved to $COOKIE_FILE"
    else
        print_error "Authentication failed. Please check your credentials."
        rm -f $COOKIE_FILE
        exit 1
    fi
}

# Function to list users
list_users() {
    print_header "Listing users..."
    
    if [ ! -f "$COOKIE_FILE" ]; then
        print_error "Not authenticated. Run '$0 auth <username> <password>' first."
        exit 1
    fi
    
    response=$(curl -s -b $COOKIE_FILE -X GET \
        "$SERVER_URL/api/user-management.php?action=list")
    
    echo "$response" | python3 -m json.tool 2>/dev/null || echo "$response"
}

# Function to create user
create_user() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        print_error "Usage: $0 create <username> <password>"
        exit 1
    fi
    
    print_header "Creating user: $1"
    
    if [ ! -f "$COOKIE_FILE" ]; then
        print_error "Not authenticated. Run '$0 auth <username> <password>' first."
        exit 1
    fi
    
    response=$(curl -s -b $COOKIE_FILE -X POST \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"$1\",\"password\":\"$2\"}" \
        "$SERVER_URL/api/user-management.php?action=create")
    
    echo "$response" | python3 -m json.tool 2>/dev/null || echo "$response"
}

# Function to delete user
delete_user() {
    if [ -z "$1" ]; then
        print_error "Usage: $0 delete <username>"
        exit 1
    fi
    
    print_header "Deleting user: $1"
    
    if [ ! -f "$COOKIE_FILE" ]; then
        print_error "Not authenticated. Run '$0 auth <username> <password>' first."
        exit 1
    fi
    
    response=$(curl -s -b $COOKIE_FILE -X POST \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"$1\"}" \
        "$SERVER_URL/api/user-management.php?action=delete")
    
    echo "$response" | python3 -m json.tool 2>/dev/null || echo "$response"
}

# Function to change password
change_password() {
    if [ -z "$1" ] || [ -z "$2" ]; then
        print_error "Usage: $0 changepass <username> <new_password>"
        exit 1
    fi
    
    print_header "Changing password for user: $1"
    
    if [ ! -f "$COOKIE_FILE" ]; then
        print_error "Not authenticated. Run '$0 auth <username> <password>' first."
        exit 1
    fi
    
    response=$(curl -s -b $COOKIE_FILE -X POST \
        -H "Content-Type: application/json" \
        -d "{\"username\":\"$1\",\"password\":\"$2\"}" \
        "$SERVER_URL/api/user-management.php?action=change_password")
    
    echo "$response" | python3 -m json.tool 2>/dev/null || echo "$response"
}

# Function to logout (clear cookies)
logout() {
    print_status "Logging out and clearing cookies..."
    rm -f $COOKIE_FILE
    print_status "Logged out successfully."
}

# Function to show status
status() {
    if [ -f "$COOKIE_FILE" ]; then
        print_status "Authenticated. Cookie file: $COOKIE_FILE"
        
        # Test authentication
        response=$(curl -s -b $COOKIE_FILE -X GET \
            "$SERVER_URL/api/user-management.php?action=list")
        
        if echo "$response" | grep -q '"status":"success"'; then
            print_status "API connection: OK"
        else
            print_warning "API connection: Failed (session may have expired)"
        fi
    else
        print_warning "Not authenticated. Run '$0 auth <username> <password>' to login."
    fi
}

# Function to show help
show_help() {
    echo "WHP User Management API Helper"
    echo ""
    echo "Usage: $0 <command> [options]"
    echo ""
    echo "Commands:"
    echo "  auth <username> <password>    Authenticate and save session cookies"
    echo "  list                          List all users"
    echo "  create <username> <password>  Create a new user"
    echo "  delete <username>             Delete a user"
    echo "  changepass <username> <pass>  Change user password"
    echo "  logout                        Clear authentication cookies"
    echo "  status                        Show authentication status"
    echo "  help                          Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 auth root mypassword"
    echo "  $0 list"
    echo "  $0 create testuser mypassword"
    echo "  $0 delete testuser"
    echo "  $0 changepass testuser newpassword"
    echo ""
    echo "Note: Only root users can access the API."
}

# Main script logic
case "$1" in
    "auth")
        authenticate "$2" "$3"
        ;;
    "list")
        list_users
        ;;
    "create")
        create_user "$2" "$3"
        ;;
    "delete")
        delete_user "$2"
        ;;
    "changepass")
        change_password "$2" "$3"
        ;;
    "logout")
        logout
        ;;
    "status")
        status
        ;;
    "help"|"--help"|"-h"|"")
        show_help
        ;;
    *)
        print_error "Unknown command: $1"
        echo "Run '$0 help' for usage information."
        exit 1
        ;;
esac 