#!/bin/bash

LOCK_PATH=/run/lock/kiwix
mkdir -p $LOCK_PATH

WAITLOCK="$LOCK_PATH/make-kiwix-lib-wait.LCK";
RUNLOCK="$LOCK_PATH/kiwix-lib-access.LCK";
KIWIXLIB={{ kiwix_library_xml }}

exec 200>$WAITLOCK;
exec 201>$RUNLOCK;

if flock -n -e 200; then :
  echo 'Waiting to run iiab-make-kiwix-lib.py'
  # wait for up to 5 min
  flock -x -w 300 201
  flock -u 200 # unlock queue
  echo "Now running iiab-make-kiwix-lib.py"
  # write to {{ kiwix_library_xml }}.tmp to minimize kiwix down
  # zim map could be out of sync for a few seconds
  # using new version that does deltas
  cp $KIWIXLIB $KIWIXLIB.tmp
  /usr/bin/iiab-make-kiwix-lib.py
  {{ systemctl_program }} stop kiwix-serve
  rm $KIWIXLIB
  mv $KIWIXLIB.tmp $KIWIXLIB
  {{ systemctl_program }} start kiwix-serve
else
  echo "Can't get wait lock for iiab-make-kiwix-lib.py";
  exit 1;
fi
echo 'Finished making Kiwix library.xml'
exit 0
