#!/bin/bash

# Script to acquire a Docker-based lock for Unity image retagging
# Usage: acquire_lock.sh <lockName>

LOCK_NAME="$1"
TIMEOUT=10
WAIT_TIME=0.2
if [ -z "$LOCK_NAME" ]; then
    echo "Error: LOCK_NAME parameter is required"
    exit 1
fi

echo "Acquiring Docker lock '$LOCK_NAME' (timeout 10s)..."

# First, wait for any existing lock to be released
START_TS=$(date +%s)
while docker image ls --format '{{.Repository}}:{{.Tag}}' | grep -qx "$LOCK_NAME"; do
    NOW_TS=$(date +%s)
    ELAPSED=$((NOW_TS - START_TS))
    if [ "$ELAPSED" -ge $TIMEOUT ]; then
        echo "Lock '$LOCK_NAME' still held after ${ELAPSED}s; proceeding anyway."
        break
    fi
    echo "Lock '$LOCK_NAME' is held by another job. Waiting $WAIT_TIME seconds... (${ELAPSED}s elapsed)"
    sleep $WAIT_TIME
done

# Now create our lock
docker pull hello-world
docker tag hello-world "$LOCK_NAME"
echo "Lock acquired: $LOCK_NAME"
