#!/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
REMOTE="$2" # Git or Rsync remote
if [ -z "$NAME" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c component)  [p$(c remote)]

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") prints the latest version of $(c component)
    available at $(c remote), or locally if $(c remote) is omitted.

  COMPONENTS:"
  say "$(ls -w 40 -m "/srv" | sed -e "s;^;    ;")
  "

  exit 1
fi

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

DIR="${COMP_DIR:-/srv}/$NAME"

# update before running this script
"$ROOT"/bin/tl-comp-sync "$NAME" "$REMOTE"
REMOTE_NAME="$(echo "$REMOTE" | sed -e 's;\(https\?\|ssh\)://;;')"

if [ -n "$REMOTE" ]; then
  tail -n1 "/$DIR/.v/$REMOTE_NAME"
else
  tail -n1 "$DIR/.v/local"
fi
