#!/usr/bin/env bash
# --- T2-COPYRIGHT-BEGIN ---
# t2/t2
# Copyright (C) 2023 - 2025 The T2 SDE Project
# SPDX-License-Identifier: GPL-2.0
# --- T2-COPYRIGHT-END ---

top=$(readlink -f $0)
[ "$top" ] && cd ${top%/*}

declare -A commands

commands["bootstrap"]="bootstrap vital deps on homebrew systems"
commands["config"]="creates a target configuration profile"
commands["install"]="installs a package and its dependencies"
commands["uninstall"]="uninstalls a package from the system"
commands["download"]="downloads assets of a package"
commands["build"]="builds a package from source"
commands["build-target"]="builds a whole target sandbox"
commands["clean"]="clean-up build artifacts"
commands["create"]="create a package from external URLs"
commands["create-iso"]="create an ISO after a target build"
commands["list-errors"]="list build target errors"
commands["commit"]="commit changes to the T2 source tree"
commands["find"]="find package based on meta data"
commands["update"]="update a package meta-data version"
commands["upgrade"]="upgrade the system install packages"
commands["up|pull"]="update / pull t2 source tree changes"
 
usage() {
    cat << EOT
Usage: t2 command <options>
Commands:
EOT

    for i in "${!commands[@]}"; do
	local desc=${commands[$i]}
	local n=$((${#i} + 2))
	local t="\t\t"
	[ $n -gt 7 ] && t="\t"
	echo -e "  $i$t$desc"
    done | sort

    cat << EOT
Options:
  -v, --verbose	verbose operation
  -c, --cfg	config name
EOT
    exit 1
}

# convert modern --* args to backward-compat single-dash -*
# and save the first non option as cmd
cmd=
declare -a args
for a; do
    a=(${a/--/-})
    [[ -z "$cmd" && "$a" = [^-]* && ( ${#args[*]} -eq 0 || ${args[-1]} != "-cfg" ) ]] && cmd="$a" && continue
    args+=($a)
done

case "$cmd" in
    conf|config) exec scripts/Config "${args[@]}" ;;
    bootstrap) exec scripts/Bootstrap "${args[@]}" ;;
    build) exec scripts/Build-Pkg "${args[@]}" ;;
    build-target) exec scripts/Build-Target "${args[@]}" ;;
    clean) exec scripts/Cleanup "${args[@]}" ;;
    create) exec scripts/Create-Pkg "${args[@]}" ;;
    create-iso) exec scripts/Create-ISO "${args[@]}" ;;
    list-errors) exec scripts/Create-ErrList "${args[@]}" ;;
    commit|ci) exec scripts/Commit "${args[@]}" ;;
    download|dl) exec scripts/Download "${args[@]}" ;;
    find) exec scripts/Find-Pkg "${args[@]}" ;;
    install|inst) exec scripts/Emerge-Pkg "${args[@]}" ;;
    update) exec scripts/Update-Pkg "${args[@]}" ;;
    upgrade) exec scripts/Emerge-Pkg -system "${args[@]}" ;;
    uninstall) exec mine -r "${args[@]}" ;;
    up|pull) if [ -e .git ]; then exec git pull; else exec svn up "${args[@]}"; fi ;;
    *) usage ;;
esac