#!/bin/bash

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOCK_FILE="$SCRIPT_DIR/import.lock"
PHP_SCRIPT="$SCRIPT_DIR/import.php"
JSON_FILE="$SCRIPT_DIR/remaining_inventories.json"

# Prevent duplicate runs
if [ -f "$LOCK_FILE" ]; then
    echo "Another instance is running. Exiting."
    exit
fi

touch "$LOCK_FILE"
echo "Lock created. Starting import loop..."

# If the JSON file doesn't exist, run the script once to generate it
if [ ! -f "$JSON_FILE" ]; then
    echo "File not found. Running PHP once to create it..."
    php "$PHP_SCRIPT"
fi

while [ -f "$JSON_FILE" ] && [ "$(jq length "$JSON_FILE")" -gt 0 ]; do
    if [ ! -f "$LOCK_FILE" ]; then
        echo "Lock removed externally. Stopping script..."
        exit
    fi
    
    echo "Running PHP import..."
    php "$PHP_SCRIPT"

    sleep 5 # Optional: wait a bit to reduce load
done

echo "No remaining records or file missing. Exiting."
rm -f "$LOCK_FILE"

echo "Creating Zip file"
php "$PHP_SCRIPT"
echo "Zip file created $SCRIPT_DIR/imglib.zip"