#!/usr/bin/env bash
# vim:et:ts=2:sts=2:sw=2

# Get absolute repository root (especially when symlinked)
ROOT="$(realpath "$(dirname "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")")")"

# Load accompanying bash library
source "$ROOT/lib/lib.bash"

NAME="$1"   # Name of component to download
REMOTE="$2" # Rsync remote
if [ -z "$NAME" ] || [ -z "$REMOTE" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c name)  $(c remote)  [$(c version)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") uploads $(c version) of
    component $(c name) to $(c remote)

    The lastest version on $(c remote) will be used by default
"
  exit 1
fi

# Exit now if run as root user
assert-is-user

say "Syncing local and remote versions"
run "$ROOT/bin/tl-comp-sync" "$NAME"
run "$ROOT/bin/tl-comp-sync" "$NAME" "$REMOTE"

V_LOCAL="$("$ROOT/bin/tl-comp-latest" "$NAME")"
V_REMOTE="$("$ROOT/bin/tl-comp-latest" "$NAME" "$REMOTE")"
V_TARGET="${3:-"$V_LOCAL"}"

say "Goal: $(c "$V_REMOTE") => $(c "$V_TARGET")"

DIR="/srv/$NAME"

if ! [[ "$NAME" =~ (desktop) ]]; then
  if grep "$V_TARGET" "$DIR/.v/$REMOTE" >/dev/null; then
    say "$(c "$V_TARGET") already uploaded to $(c "$REMOTE")"

  else
    run ssh "$REMOTE" mkdir -p "/srv/$NAME/.rsync"

    success=true
    for src in "$DIR/v$V_TARGET"*; do
      run rsync --cc=xxh3 --partial --append-verify -avzP \
        "$src" "$REMOTE:/srv/$NAME/.rsync"
      if [ $? -ne 0 ]; then
        success=false
        break
      fi

      if "$success"; then
        echo "$ver" >>"$DIR/.v/$REMOTE"
        run ssh "$REMOTE" mv "/$DIR/.rsync/v$V_TARGET"* "$DIR"
        say "$(c "$ver") uploaded"
      else
        err "Upload failed!"
      fi

    done
  fi

else
  # The patch version -- x.x.x
  PATCH="$V_TARGET"
  # The minor version -- x.x.0
  MINOR="$(echo "$PATCH" | cut -d. -f-2).0"
  # The major version -- x.0.0
  MAJOR="$(echo "$PATCH" | cut -d. -f-1).0.0"

  say "MAJOR=$MAJOR MINOR=$MINOR PATCH=$PATCH"

  for ver in "$MAJOR" "$MINOR" "$PATCH"; do
    if grep "$ver" "$DIR/.v/$REMOTE" >/dev/null; then
      say "$(c "$ver") already uploaded to $(c "$REMOTE")"
      continue
    fi

    say "Uploading $(c "$ver")"
    success=true
    for src in "$DIR/v$ver"*; do
      rsync --cc=xxh3 --partial -avzP --append-verify "$src" "$REMOTE:/srv/$NAME"
      if [ $? -ne 0 ]; then
        success=false
        break
      fi
    done
    if "$success"; then
      echo "$ver" >>"$DIR/.v/$REMOTE"
    fi
  done
fi

say "Up-to-date."
exit
