#!/bin/bash
# Container Monitoring and Auto-Restart Script
# Monitors Plex, Jellyfin, and Immich containers using Podman (Docker commands are ignored)

LOGFILE="/home/rogeryu/Documents/logs/container-monitor.log"

# Ensure Plex transcode directory exists (tmpfs cleared on reboot)
mkdir -p /tmp/transcode

# Generate timestamp for each log entry
log_message() {
    local ts=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$ts] $1" >> "$LOGFILE"
}

# List of containers to monitor (match names used in Podman)
CONTAINERS=("plex" "jellyfin" "immich_server" "immich_postgres" "immich_redis" "immich_machine_learning")

# Process each container
for container in "${CONTAINERS[@]}"; do
    # Check if container is running
    running=$(podman ps -q -f "name=$container")
    
    if [ -z "$running" ]; then
        log_message "WARNING: Container $container is not running. Attempting restart..."
        
        # Attempt to start container
        podman start "$container" > /dev/null 2>&1
        status=$?
        
        if [ $status -eq 0 ]; then
            log_message "SUCCESS: Container $container restarted (exit $status)"
        else
            log_message "ERROR: Failed to restart $container (exit $status)"
        fi
    else
        log_message "INFO: Container $container is running normally"
    fi
done

# Keep log file manageable (keep last 100 lines)
if [ -f "$LOGFILE" ]; then
    tail -100 "$LOGFILE" > "$LOGFILE.tmp" && mv "$LOGFILE.tmp" "$LOGFILE"
fi