#!/bin/bash
# Pre-removal script for rpi-power-hat

set -e

echo "Preparing to remove rpi-power-hat..."

# Action argument (remove|upgrade|purge). Default to remove if not provided
ACTION="${1:-remove}"

# Stop any running monitoring processes
echo "Stopping any running rpi-power-hat processes..."
pkill -f "rpi-power-hat.*log-current" 2>/dev/null || true
pkill -f "rpi-power-hat.*log-power" 2>/dev/null || true

# Clean up any temporary files in various possible locations
echo "Cleaning up temporary files..."
for TEMP_DIR in "${TMPDIR:-/tmp}" "/var/tmp" "/tmp"; do
    [ -d "$TEMP_DIR" ] || continue
    rm -f "$TEMP_DIR"/current_logger.pid 2>/dev/null || true
    rm -f "$TEMP_DIR"/power_logger.pid 2>/dev/null || true
    rm -f "$TEMP_DIR"/current_logger_temp* 2>/dev/null || true
    rm -f "$TEMP_DIR"/power_logger_temp* 2>/dev/null || true
done

# Remove symbolic link if it exists
if [ -L /usr/bin/power-hat ]; then
    echo "Removing compatibility symbolic link..."
    rm -f /usr/bin/power-hat
fi

# Do not remove files under /dev here; udev manages device nodes and symlinks

# On package removal (not upgrade), clean up runtime data and logs
if [ "$ACTION" != "upgrade" ]; then
    echo "Removing rpi-power-hat runtime data and logs..."
    # Remove runtime data under /var/lib
    rm -rf /var/lib/rpi-power-hat/working 2>/dev/null || true
    rm -rf /var/lib/rpi-power-hat/keys 2>/dev/null || true
    rm -rf /var/lib/rpi-power-hat/history 2>/dev/null || true
    rm -rf /var/lib/rpi-power-hat/images 2>/dev/null || true
    rm -rf /var/lib/rpi-power-hat/logs 2>/dev/null || true
    # Remove base directories if empty or regardless
    rm -rf /var/lib/rpi-power-hat 2>/dev/null || true
    
    # Remove logs directory
    rm -rf /var/log/rpi-power-hat 2>/dev/null || true
fi

echo "rpi-power-hat pre-removal cleanup completed."

exit 0
