#!/usr/bin/env bash

# From gregory
# I wrote none of this. This script is produced entirely by AI

# Function to get battery percentage
get_battery_percentage() {
    local bat_path="/sys/class/power_supply"
    local bat_name=""
    
    # Find battery directory
    for bat in "$bat_path"/BAT*; do
        if [ -d "$bat" ]; then
            bat_name=$(basename "$bat")
            break
        fi
    done
    
    if [ -z "$bat_name" ]; then
        echo "BATTERY_NOT_FOUND"
        return 1
    fi
    
    local capacity_file="$bat_path/$bat_name/capacity"
    if [ ! -r "$capacity_file" ]; then
        echo "CAPACITY_READ_FAILED"
        return 1
    fi
    
    local capacity
    if ! capacity=$(cat "$capacity_file" 2>/dev/null); then
        echo "CAPACITY_READ_FAILED"
        return 1
    fi
    
    # Validate it's a number between 0-100
    if ! echo "$capacity" | grep -qE '^[0-9]+$'; then
        echo "CAPACITY_INVALID"
        return 1
    fi
    
    if [ "$capacity" -lt 0 ] || [ "$capacity" -gt 100 ]; then
        echo "CAPACITY_INVALID"
        return 1
    fi
    
    echo "$capacity"
}

# Function to get battery status
get_battery_status() {
    local bat_path="/sys/class/power_supply"
    local bat_name=""
    
    # Find battery directory
    for bat in "$bat_path"/BAT*; do
        if [ -d "$bat" ]; then
            bat_name=$(basename "$bat")
            break
        fi
    done
    
    if [ -z "$bat_name" ]; then
        echo "BATTERY_NOT_FOUND"
        return 1
    fi
    
    local status_file="$bat_path/$bat_name/status"
    if [ ! -r "$status_file" ]; then
        echo "STATUS_READ_FAILED"
        return 1
    fi
    
    local status
    if ! status=$(cat "$status_file" 2>/dev/null); then
        echo "STATUS_READ_FAILED"
        return 1
    fi
    
    # Validate status is one of expected values
    case "$status" in
        Charging|Discharging|Full|Unknown|"Not charging")
            echo "$status"
            ;;
        *)
            echo "STATUS_UNKNOWN"
            return 1
            ;;
    esac
}

# Function to get date
get_date() {
    if ! date +%Y-%m-%d 2>/dev/null; then
        echo "DATE_FAILED"
        return 1
    fi
}

# Function to get time with seconds
get_time() {
    if ! date +%H:%M:%S 2>/dev/null; then
        echo "TIME_FAILED"
        return 1
    fi
}

# Main loop
while true; do
    # Get all components
    battery_percent=$(get_battery_percentage)
    battery_status=$(get_battery_status)
    current_date=$(get_date)
    current_time=$(get_time)
    
    # Print the line
    echo "${battery_percent}% ${battery_status}     ${current_date}    ${current_time}"
    
    # Wait 1 second
    sleep 1
done
