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

COMP="${1}"               # Component to install
DEST="${3:-"/opt/$COMP"}" # Directory to unpack

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

  DESCRIPTION:
    $(g "${BASH_SOURCE##*/}") unpacks a $(c component) archive into $(c destination)
                                                          (default: $(c /opt/$(g comp)))

    The lastest local version will be used by default

  NOTE:
    If no archives are available, use $(g tl-comp-pull) to download one
"
  exit 1
fi

# Exit now if run as the admin user
assert-is-admin

say "Syncing $COMP versions"
"$ROOT/bin/tl-comp-sync" "$COMP"

# The version -- x.x.x
VERSION="${2:-"$("$ROOT/bin/tl-comp-latest" "$COMP")"}"

TEMPDIR="$(mktemp -d)"

say "Unpacking archive"
run tar -xzf "/srv/$COMP/v$VERSION.tar.gz" -C "$TEMPDIR"

say "Replacing existing version"
run rm -rf "$DEST/"*
run rsync -az "$TEMPDIR/"{*,.version,.changelog} "$DEST"
run rm -rf "$TEMPDIR"

say "Done. $(c $COMP) v$(c $VERSION) is installed at $(c $DEST)"
