#!/bin/bash
# Send multiple files to FTP, with resume/delete until no error
if [ $# -lt 1 ]; then
        echo "Usage: $0 <file1> [<file2> ...]"
        exit 1
fi

source /etc/ftpbackup.conf
E=0
while : ; do
  F="$1"
  shift
  [ -z "$F" ] && break # no more files
  [ -f "$F" ] || continue # file does not exist
  for j in {1..30}; do # max tries to rm
    echo -n "Sending $F ($(ls -lh $F |awk '{print $5}')B) "
    for i in {1..20}; do # max tries to upload
      echo -n "."
      curl --silent --continue-at - --globoff --upload-file "$F" "ftp://$USER:$PASS@$HOST:$PORT/"
      R=$?
      [ $R -eq 0 ] && break
      sleep 1
    done
    [ $R -eq 0 ] && break
    # failed too many times: delete & retry
    echo " failed, retrying"
    echo "rm $(basename $F)" |ftpbackup-connect 2>/dev/null
    sleep 1
  done
  [ $R -eq 0 ] && echo " OK" || { echo "Giving up, send $F failed"; E=$[$E+1]; }
done

# exit number of errors
[ $E -gt 127 ] && E=127
exit $E
