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

components=("curriculum" "desktop" "snapshots" "admin" "control" "help")
for comp in "${components[@]}"; do
  say "Syncing latest (c $comp) versions"
  run "$ROOT"/bin/tl-comp-sync "$comp"

  d="/srv/$comp"
  v="$d/.v"

  if ! [ -d "$v" ]; then
    echo "$comp.versions.synced-at" "null"
  else
    echo "$comp.versions.synced-at" "$(cat "$v/.synced-at")"

    for remote in $(ls "$v"); do
      echo "$comp.versions.$remote.latest" "$(tail -n1 "$v/$remote")"
      echo "$comp.versions.$remote.all" "$(echo $(cat "$v/$remote" | sort -r) | tr ' ' ',')"
    done
  fi

  if [[ -f "/opt/$comp/.version" ]]; then
    echo "$comp.versions.installed $(cat "/opt/$comp/.version" | tail -n1)"

  elif [[ "$comp" == "curriculum" ]] && [[ -f "/var/btrfs/@guest/Desktop/.version" ]]; then
    echo "$comp.versions.installed $(cat "/var/btrfs/@guest/Desktop/.version" | tail -n1)"

  elif [[ "$comp" == "desktop" ]] && [[ -f "/etc/tl-desktop-version" ]]; then
    echo "$comp.versions.installed $(cat "/etc/tl-desktop-version" | tail -n1)"
  fi

  echo "$comp.storage.path" "$d"
  echo "$comp.storage.size" "$(du -sxh "$(readlink -f "$d")" | awk '{print $1}')"
done
