#!/usr/bin/env bash
# dmmotor: sends the wads/ folder (with its sub-folders) to the production server, with rsync over SSH.
#
#   games/dmmotor/tools/push-wads.sh             send what is new or changed
#   games/dmmotor/tools/push-wads.sh --dry-run   show what would be sent, send nothing
#   games/dmmotor/tools/push-wads.sh --delete    also delete on the server what is no longer in wads/
#
# The server is set in games/dmmotor/tools/push-wads.conf (NOT versioned: copy push-wads.conf.example).
# wads/.syncignore lists the folders / files never sent (rsync patterns, one a line).
# Only send WADs you have the right to put on that server.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
GAME="$(cd "$HERE/.." && pwd)"
SRC="$GAME/wads/"
CONF="$HERE/push-wads.conf"

die() { echo "push-wads: $*" >&2; exit 1; }

[ -f "$CONF" ] || die "no $CONF: cp $HERE/push-wads.conf.example $CONF, then set the server in it"
# shellcheck source=/dev/null
. "$CONF"
[ -n "${WADS_HOST:-}" ] || die "WADS_HOST is empty in $CONF (user@server)"
[ -n "${WADS_DIR:-}" ] || die "WADS_DIR is empty in $CONF (the wads/ folder of the game on the server)"
[ -d "$SRC" ] || die "no folder $SRC"
command -v rsync >/dev/null || die "rsync is missing (sudo apt install rsync)"

DRY=()
DELETE=()
for arg in "$@"; do
  case "$arg" in
    -n|--dry-run) DRY=(--dry-run) ;;
    --delete) DELETE=(--delete) ;;
    -h|--help) sed -n '2,10p' "$0"; exit 0 ;;
    *) die "unknown option $arg (--dry-run, --delete)" ;;
  esac
done

IGNORE=()
[ -f "${SRC}.syncignore" ] && IGNORE=(--exclude-from="${SRC}.syncignore")

# without WADS_PORT / WADS_KEY, ssh uses ~/.ssh/config for that host (user, port, key)
SSH=(ssh)
[ -n "${WADS_PORT:-}" ] && SSH+=(-p "$WADS_PORT")
[ -n "${WADS_KEY:-}" ] && SSH+=(-i "$WADS_KEY")

echo "push-wads: $SRC -> $WADS_HOST:$WADS_DIR ${DRY:+(dry run)}${DELETE:+ (with --delete)}"
# the folder on the server, created if needed
[ ${#DRY[@]} -eq 0 ] && "${SSH[@]}" "$WADS_HOST" "mkdir -p '$WADS_DIR'"

# -a: sub-folders, dates, rights; -z: compressed; --partial: a cut upload goes on next time
rsync -az --partial --human-readable --info=progress2,stats1 \
  "${DRY[@]}" "${DELETE[@]}" \
  --exclude '.DS_Store' --exclude 'Thumbs.db' --exclude '*.tmp' --exclude '.git/' \
  ${IGNORE[@]+"${IGNORE[@]}"} \
  ${WADS_CHOWN:+--chown="$WADS_CHOWN"} \
  -e "${SSH[*]}" \
  "$SRC" "$WADS_HOST:$WADS_DIR/"

echo "push-wads: done"
