#!/bin/bash
#
# Script to check for a zero-sized cloud.ks file and perform corrective actions.
# If cloud.ks exists and its size is zero, it stops and removes the BEMS Docker container,
# deletes cloud.ks, and then restarts the BEMS container.
#

WORKDIR="/home/pi/ehc602/backend"
CLOUD_KS_FILE="/home/pi/docker/etc/finEdge2Cloud/cloud.ks"
BEMS_SCRIPTS_DIR="$WORKDIR/bems"
GET_CONTAINER_NAME_SCRIPT="$BEMS_SCRIPTS_DIR/get-container-name.py"
START_CONTAINER_SCRIPT="$BEMS_SCRIPTS_DIR/start-container.py"
BEMS_CONFIG_FILE="$WORKDIR/properties/factory/bems-config.json" # Path derived from patch.sh

# Ensure necessary scripts are executable
chmod +x "$GET_CONTAINER_NAME_SCRIPT" 2>/dev/null || true
chmod +x "$START_CONTAINER_SCRIPT" 2>/dev/null || true

# Check if cloud.ks exists and its size is zero
if [ -f "$CLOUD_KS_FILE" ] && [ ! -s "$CLOUD_KS_FILE" ]; then
    echo "Found zero-sized $CLOUD_KS_FILE. Initiating container stop, removal, file deletion, and restart."

    # Get container name
    CONTAINER_NAME=$(python3 "$GET_CONTAINER_NAME_SCRIPT" --conffile="$BEMS_CONFIG_FILE")
    if [ -z "$CONTAINER_NAME" ]; then
        echo "Error: Could not determine container name using $GET_CONTAINER_NAME_SCRIPT. Aborting."
        exit 1
    fi
    echo "Container name detected: $CONTAINER_NAME"

    # Stop the running container
    echo "Attempting to stop container '$CONTAINER_NAME'..."
    # Use 'docker stop' with a timeout (e.g., 10 seconds)
    if docker stop -t 10 "$CONTAINER_NAME"; then
        echo "Container '$CONTAINER_NAME' stopped successfully."
    else
        echo "Warning: Could not gracefully stop container '$CONTAINER_NAME'. Attempting forceful removal."
    fi

    # Delete the cloud.ks file
    echo "Deleting $CLOUD_KS_FILE..."
    if rm "$CLOUD_KS_FILE"; then
        echo "$CLOUD_KS_FILE deleted successfully."
    else
        echo "Error: Failed to delete $CLOUD_KS_FILE. Manual intervention may be required. Aborting restart."
        exit 1
    fi

    # Restart the container using the start-container.py script
    echo "Starting container '$CONTAINER_NAME'..."
    if docker start "$CONTAINER_NAME"; then
        echo "Container '$CONTAINER_NAME' started successfully."
    else
        echo "Error: Could not start container '$CONTAINER_NAME'."
    fi

else
    echo "$CLOUD_KS_FILE does not exist or has a non-zero size. No action taken."
    $BEMS_SCRIPTS_DIR/start-container.sh &
fi
