#!/bin/bash

SCRIPT_DIR="/home/softwareflare/psx.softwareflare.com/broward-ftlauderdale"
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..."

while [ -f "$JSON_FILE" ] && [ "$(jq length "$JSON_FILE")" -gt 0 ]; do
    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"
