#!/bin/bash

# Minimum battery percentage required to run unattended upgrades
THRESHOLD=50

# Log file path
LOGFILE="/var/log/unattended-wrapper.log"
# Current date and time
DATE="$(date '+%Y-%m-%d %H:%M:%S')"

# Logging function: logs to file and to systemd journal
log() {
    echo "[$DATE] $1" | tee -a "$LOGFILE"
    logger -t unattended-wrapper "$1"
}

# Find the battery path (e.g., /sys/class/power_supply/BAT0)
BATTERY_PATH=$(find /sys/class/power_supply/ -name 'BAT*' | head -n 1)
if [[ -n "$BATTERY_PATH" ]]; then
    # Read current battery percentage and charging status
    CAPACITY=$(cat "$BATTERY_PATH/capacity")
    STATUS=$(cat "$BATTERY_PATH/status")
    if [[ "$STATUS" != "Charging" && "$STATUS" != "Full" && "$CAPACITY" -lt "$THRESHOLD" ]]; then
        log "Battery insufficient ($CAPACITY%, status: $STATUS). Skipping unattended upgrades." 
        exit 1
    fi
    log "Battery sufficient ($CAPACITY%, status: $STATUS). Starting unattended upgrades." 
else
    log "No battery detected, I assume fixed system. Starting unattended upgrades." 
fi

exit 0
