#!/bin/bash

#
# This script handles uploader actions
#

# The spool dir where uploader looks for action files
SPOOLDIR=/var/spool/raperca

# PID file
PIDFILE=/var/run/uploader.pid

# The name of the resume file (without directory path)
RESUMEFILE=action-0000-resume.xml

# This cleans up all possibly stray action files from previous boots
cleanup() {
    rm -f "$SPOOLDIR"/"$RESUMEFILE" "$SPOOLDIR"/.tmp."$RESUMEFILE"
}

# This resumes the queues which are normally started in pause mode
resume() {
    # Go through tmp file to avoid race condition with uploader where it
    # could read the file before it is written
    cat > "$SPOOLDIR"/.tmp."$RESUMEFILE" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<action xmlns="http://www.spinetix.com/namespace/1.0/spxproj"
  summary="resume" location="publish" />
EOF
    [ $? -eq 0 ] && mv "$SPOOLDIR"/.tmp."$RESUMEFILE" "$SPOOLDIR"/"$RESUMEFILE"
    if [ $? -ne 0 ]; then
	echo "failed creating uploader resume file" >&2
	return 1
    fi
    # Signal uploader to rescan actions ASAP
    [ -s "$PIDFILE" ] && kill -USR2 "$(< "$PIDFILE")"
    return 0
}

#
# Main
#

case "$1" in
    cleanup)
	cleanup
	;;
    resume)
	resume
	;;
    *)
	echo "$0: invalid action '$1'" >&2
	echo "actions: cleanup | resume" >&2
	;;
esac
