#! /bin/bash -e prog=${0##*/} tmp=${DVDRIP_TMPDIR-${HOME?}/tmp/dvdrip} archive=${DVDRIP_ARCHIVE-jem.distorted.org.uk:/mnt/dvd/archive} kill=nil listen=nil verbose=nil bogus=nil opts=; unset dir sub n label usage () { cat <&2; exit 2 ;; esac case $verbose in t) set -x ;; esac notify () { colour=$1 message=$2 echo "$(tput bold; tput setaf $colour)$message$(tput sgr0; tput op)" } fail () { notify 1 "!!! $*"; exit 2; } warn () { notify 5 "??? $*"; } info () { notify 6 "--- $*"; } run_setrc () { notify 2 "+++ $*"; set +e; nice "$@"; rc=$?; set -e } run () { run_setrc "$@"; case $rc in 0) ;; *) fail "$1: exit $rc" ;; esac; } case $archive in *:*) archhost=${archive%%:*} archpath=${archive#*:} ;; *) unset archhost; archpath=$archive ;; esac archdo () { op=$1; shift case ${archhost+t} in t) qq= for a in "$@"; do qq="${qq:+$qq }'${a//\'/"'\\''"}'" #" # emacs is confused done "$op" ssh "$archhost" "$qq" ;; *) "$op" "$@" ;; esac } archrun () { archdo run "$@"; } check () { info "checking for pending uploads" while :; do any=nil for i in "$tmp"/*; do if [ -f "$i/dest" ]; then read dest <"$i/dest"; any=t mv "$i/dest" "$i/dest.seen" (info "copy $i/iso -> $dest" case $dest in */*) dir=${dest%/*} ;; *) dir= ;; esac archrun mkdir -p "$archpath${dir:+/$dir}" run rsync -svP --inplace --bwlimit 728k "$i/iso" "$archive/$dest" run rm -rf "$i") || : fi done case $any in nil) break ;; esac done info "all done" } try_kick_daemon () { sig=$1 if [ -f "$tmp/upload.pid" ]; then daemon=$(cat "$tmp/upload.pid") case $daemon in "" | *[!0-9]*) ;; *) if kill -$sig $daemon >/dev/null 2>&1; then return 0; fi ;; esac fi return 1 } try_kill () { victim=$1 case $victim in nil) ;; *) kill $victim >/dev/null 2>&1 || : ;; esac } case $kill,$listen in t,t) fail "inconsistent options \`-k' and \`-l'" ;; t,nil) if ! try_kick_daemon TERM; then fail "failed to kill listener"; fi ;; nil,t) if try_kick_daemon 0; then fail "daemon already running (pid $daemon)"; fi trap 'try_kill $sleepy; rm -f "$tmp/upload.pid"' EXIT trap 'info "quitting on user request"; exit 0' INT TERM trap 'try_kill $sleepy' HUP echo $$ >"$tmp/upload.pid.new" mv "$tmp/upload.pid.new" "$tmp/upload.pid" while :; do sleep 3600& sleepy=$! check wait $sleepy || :; sleepy=nil done ;; nil,nil) if ! try_kick_daemon HUP; then check; fi ;; esac