#!/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" # Git or 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##*/}") downloads $(c version) of
    component $(c name) from $(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

DIR="/srv/$NAME"
CLIENT="${DOWNLOAD_CLIENT:-$(echo "$REMOTE" | grep -Eq '^(http|https)://' && echo 'aria2' || echo 'rsync')}"
REMOTE_NAME="$(echo "$REMOTE" | sed -e 's;\(https\?\|ssh\)://;;')"

say "Syncing local and remote versions"
V_LOCAL="$("$ROOT/bin/tl-comp-latest" "$NAME")"
V_REMOTE="$("$ROOT/bin/tl-comp-latest" "$NAME" "$REMOTE")"
V_TARGET="${3:-"$V_REMOTE"}"

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

#   && CLIENT=rsync

# USAGE: download 0.8.20 /srv/admin/.rsync
# Returns download exit code
download() {
  local ver=v"$1"
  local dir="$2"

  local base_url="http://$REMOTE_NAME/$NAME/$ver"
  local urls=("$base_url.tar.gz" "$base_url.sha256")
  [[ "$NAME" =~ desktop ]] && urls+=("$base_url.changelog")
  [[ "$NAME" =~ recovery ]] && urls=("$base_url.iso" "$base_url".sha256)

  if [ "$CLIENT" = 'aria2' ]; then
    run aria2c --continue -d "$dir" -P -Z "${urls[@]}"
    return $?
  else
    run rsync --cc=xxh3 -avzP --partial --append-verify \
      "$REMOTE_NAME:/srv/$NAME/$ver".* "$dir"
    return $?
  fi
}

if ! [[ "$NAME" =~ desktop ]]; then
  if grep "$V_TARGET" "$DIR/.v/local" >/dev/null; then
    say "$(c "$V_TARGET") already downloaded"
  else
    run mkdir -p "$DIR/.rsync"

    if download "$V_TARGET" "$DIR/.rsync"; then
      echo "$ver" >>"$DIR/.v/local"
      say "$(c "$ver") downloaded"
      run mv "$DIR/.rsync/v$V_TARGET"* "$DIR"
      say "Up-to-date."
    else
      err "Failed to pull "$NAME" $(c $ver)"
    fi

  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" "/srv/snapshots/.v/local" >/dev/null; then
      say "$(c "$ver") already downloaded"
      continue
    fi

    say "Downloading $(c "$ver")"
    if download "$ver" "$DIR"; then # Don't use a temp dir for Desktop
      echo "$ver" >>"$DIR/.v/local"
      say "$(c "$ver") downloaded"
    else
      err "Failed to pull desktop $(c $ver)"
    fi

  done
fi
