#!/bin/sh
set -e

if test '(' "$2" = 'all' ')' -o '(' $# -eq 0 -a -z "$SERVER" ')'; then
  for website in $(ls --ignore='scripts' --ignore='sshkeys' /web); do
    "$0" "$website"
  done
  echo "finished all downloads"
  exit
fi

function download {
  echo "start downloading from $1"
  if test -f "/web/scripts/sftp-$1.sh"; then
    echo "get -Rp / /web/$1" | "/web/scripts/sftp-$1.sh" -b -
    echo "finished downloading $website"
    return 0
  else
    echo "could not find connection script '/web/scripts/sftp-$1.sh', skip $1" >&2
    return 1
  fi
}

if test $# -eq 0; then
  download "$SERVER"
elif test "$2" != 'none'; then
  for website in "$@"; do
    download "$website"
  done
fi
