#!/bin/bash
# 
# Run arbitrary scripts in scripts-once.d, but once only
# 
# Scripts need to have a unique internal tag in one of two forms:
#   tag: <tag>
#   arch-id: <tag>
# <tag> must be a unique token without spaces - a 'uuidgen' uuid is recommended
#

CACHEDIR=/var/cache/xsync/scripts-once.d
if [ ! -d $CACHEDIR ]; then
  echo "ERROR: cache dir $CACHEDIR not found - skipping all scripts-once.d scripts"
  exit 1
fi

TYPE=script
. `dirname $0`/xsync_functions
xsync_setup $*

pkglist=
for i in $DIR/$ME.d/*; do
  j=`basename $i`
  test -x $i || continue
  # Find first tag
  TAG=`egrep '(tag|arch-id):[[:space:]]*[^[:space:]]+' $i | head -1`
  if [ -z "$TAG" ]; then
    echo "WARNING: no tag found in $i - skipping"
    continue
  fi
  TAG=`echo $TAG | sed -re 's/^.*(tag|arch-id):[[:space:]]*([^[:space:]]+).*$/\2/'`
  if [ -z "$TAG" ]; then
    echo "ERROR: extracting tag from $i failed - skipping"
    continue
  fi
  # Run
  CACHEFILE="$CACHEDIR/$TAG"
  test -f "$CACHEFILE" && continue
  if [ -n "$ECHO" ]; then
    echo "Running $i"
  else
    test -n "$QUIET" || echo "[ $i ]"
    $i && touch $CACHEFILE
  fi
done

