diff options
-rwxr-xr-x | share/hydractl/sync-media | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/share/hydractl/sync-media b/share/hydractl/sync-media index 498b247..08d6280 100755 --- a/share/hydractl/sync-media +++ b/share/hydractl/sync-media @@ -17,6 +17,7 @@ CACHE="/var/cache/$HOST/media" MEDIA="media.$DOMAIN" INCOMING="$CACHE/incoming" WHOAMI="`whoami`" +LOCK=".sync-media.lock" OPTIONS="$*" # Dependencies @@ -24,6 +25,56 @@ hydra_install_package rsync hydra_install_package unison hydra_install_package git-annex +# Fatal error +# Adapted from borger +function fatal { + info [fatal] $* + exit 1; +} + +# Create lockfile +# Adapted from borger +function sync_media_set_lockfile { + if [ ! -z "$LOCKFILE" ]; then + mkdir -p `dirname $LOCKFILE` + + if ( set -o noclobber; echo "$$" > "$LOCKFILE" ) &> /dev/null; then + trap 'sync_media_unset_lockfile' INT TERM EXIT + else + fatal "Could not create lockfile $LOCKFILE, exiting" + fi + fi +} + +# Remove lockfile +# Adapted from borger +function sync_media_unset_lockfile { + if [ ! -z "$LOCKFILE" ]; then + rm -f $LOCKFILE || echo "Could not remove lockfile $LOCKFILE" + fi +} + +# Check lockfile +# Adapted from borger +function sync_media_check_lockfile { + local pid process + + if [ ! -z "$LOCKFILE" ] && [ -f "$LOCKFILE" ]; then + pid="`cat $LOCKFILE`" + process="`ps --no-headers -o comm $pid`" + + git annex unannex $LOCK + git ignore $LOCK + + if [ "$?" == "0" ] && [ "`ps --no-headers -o comm $$`" == "$process" ]; then + fatal "Another program is running for $LOCKFILE, skipping run" + else + echo "Found old lockfile $LOCKFILE, removing it" + sync_media_unset_lockfile + fi + fi +} + # Fix identity function sync_media_identity { if [ -z "`git config --local user.email`" ] || [ -z "`git config --local user.name`" ]; then @@ -223,6 +274,8 @@ fi # Iterate over existing repositories in the local cache for folder in $REPOSITORIES; do + LOCKFILE="$CACHE/$folder/$LOCK" + # Sync each repository in the local cache if [ -d "$CACHE/$folder/.git/annex" ]; then if [ "`git -C $CACHE/$folder config sync-media.skip`" == "true" ]; then @@ -233,6 +286,10 @@ for folder in $REPOSITORIES; do cd $CACHE/$folder echo "Syncing $CACHE/$folder..." + # Lockfile handling + sync_media_check_lockfile + sync_media_set_lockfile + # Ensure the removable volume is in the list of remotes sync_media_ensure_remote $REMOTE $VOLUME/$MEDIA/$folder @@ -266,6 +323,9 @@ for folder in $REPOSITORIES; do sync_media_dropunused git prune git gc + + # Unset the lockfile + sync_media_unset_lockfile ) fi |