#!/usr/bin/env python3
"""Tiny shared-file lock for agents editing the same kill file. Usage:
  python3 _tools/flock58.py take <file> <who>   -> exit 0 if taken, 1 if someone holds it (prints who/since)
  python3 _tools/flock58.py drop <file> <who>
Locks live in /Volumes/Workspace/Scratch/coord/locks; a lock older than 20 min counts as stale and can be taken."""
import os, sys, time, json
D = '/Volumes/Workspace/Scratch/coord/locks'
act, f, who = sys.argv[1], os.path.basename(sys.argv[2]), sys.argv[3]
p = os.path.join(D, f + '.lock')
if act == 'take':
    try:
        if os.path.exists(p):
            L = json.load(open(p))
            if L['who'] != who and time.time() - L['t'] < 1200: print('HELD by %s for %ds' % (L['who'], time.time() - L['t'])); sys.exit(1)
            os.remove(p)
        fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY); os.write(fd, json.dumps({'who': who, 't': time.time()}).encode()); os.close(fd); print('TAKEN'); sys.exit(0)
    except FileExistsError: print('HELD (race)'); sys.exit(1)
elif act == 'drop':
    if os.path.exists(p) and json.load(open(p))['who'] == who: os.remove(p)
    print('DROPPED')
