#!/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"

# Defaults
SUBJECT=""
REMOTE="" # Git or Rsync remote
DIR=""
SYNC_ARGS="$NAME"

# Determine paths and arguments based on component type
if [ "$NAME" = "curriculum" ]; then
  SUBJECT="$2"
  REMOTE="$3"

  # If subject is missing or looks like a remote, show help
  if [ -z "$SUBJECT" ] || [[ "$SUBJECT" =~ ^(https?|ssh):// ]] || [[ "$SUBJECT" =~ \.local$ ]]; then
    HELP=true
  fi

  DIR="${COMP_DIR:-/srv}/curriculum/$SUBJECT"
  SYNC_ARGS="$NAME $SUBJECT"
else
  REMOTE="$2"
  DIR="${COMP_DIR:-/srv}/$NAME"
fi

if [ -z "$NAME" ] || [ -n "$HELP" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  say "
  USAGE:
    $(g "${BASH_SOURCE##*/}")  $(c component) [$(c subject)] [$(c remote)]

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

    If $(c component) is 'curriculum', a $(c subject) must be provided.

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

  exit 1
fi

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

# update before running this script
"$ROOT"/bin/tl-comp-sync $SYNC_ARGS "$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
