#!/usr/bin/env bash

set -e
set -o nounset
set -o pipefail

SCRIPTS=${SCRIPTS:-$HOME/.local/scripts}
THIS_FILE=${BASH_SOURCE[0]}
LOG_LABEL=$(basename "$THIS_FILE")
THIS=${THIS:-$LOG_LABEL}
LOG_FILE=${LOG_FILE:-"$LOG_LABEL.log"}
XDG_DATA_HOME=${XDG_DATA_HOME:-"$HOME/.local/share"}
XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-"$HOME/.config"}
DEV_ENV=${DEV_ENV:-""}
KBD=${KBD:-""} # Keyboard config to use, either "voyager" or "macbook"

usage() {
	cat <<EOF

Manages kanata qmk keyboard program, which needs to be built locally. Also manages the kanata systemd service.

USAGE:

  $ $THIS <command> <flags>

FLAGS:
  -h | --help:    Show this help page.

COMMANDS:
  config:         Commands for the kanata keyboard configuration file(s).
  service:        Commands for the kanata systemd service.
  logs:           View the log file.

Run "$THIS <command> --help" for more information about a command.

EOF
}

# Logging utility function, use in place of echo.
log() {
	logging log --source "$THIS_FILE" "$@"
}

################################################################################
# MAIN
################################################################################

# Setup logging file and label.
source "$SCRIPTS/hypr/logging"
setup-logging "$LOG_FILE" "$LOG_LABEL"

while [[ $# -gt 0 ]]; do
	if [[ $1 == "-h" ]] || [[ $1 == "--help" ]]; then
		usage && exit 0
	elif [[ $1 == "config" ]]; then
		shift
		THIS="$THIS config" $SCRIPTS/utils/kanatactl/config "$@"
		exit $?
	elif [[ $1 == "service" ]]; then
		shift
		THIS="$THIS service" $SCRIPTS/utils/kanatactl/service "$@"
		exit $?
	elif [[ $1 == "logs" ]]; then
		bat ${LOG_DIR:-/tmp/logs}/$LOG_FILE && exit 0
	elif [[ $1 == "update" ]]; then
		install_or_update "Updating" && exit 0
	else
		break
	fi
done

# If we've made it here, then we didn't handle the command.
usage && exit 1
