#! /bin/bash
#
# mclevel
# Uses xdotool and an Ars Magica 2 Journal to give you levels
# Takes a desired level and outputs right clicks in 100xp increments, basically
# Copyright (C) 2019 Vintage Salt <rehashedsalt@cock.li>
#
# Distributed under terms of the MIT license.
#
set -e
# Read-only globals
declare -r _name="$(basename -- "$0")"
# Globals
declare -i _opthelp
declare -i _level

# Helper functions
log() {
	# Print a line to the terminal if _optverbose is greater than $2
	# $2 defaults to 0
	# loglevel 0: Daily-use messages
	# loglevel 1: Detailed but not quite debugging
	# loglevel 2: Definitely debugging
	[ -z "$1" ] && return 1
	if (( _optverbose >= ${2:-0} )); then
		printf "%s\\n" "$1"
	fi
}
warn() {
	# Print a yellow line to the terminal, respecting _optverbose
	[ -z "$1" ] && return 1
	if (( _optverbose >= ${2:-0} )); then
		if [ -t "$outstream" ]; then
			printf "\\e[33m%s\\e[0m\\n" "$1"
		else
			printf "WARN: %s\\n" "$1"
		fi
	fi
}
error() {
	# Print a red line to the terminal, exit if $2 is specified
	[ -z "$1" ] && return 1
	if [ -t 2 ]; then
		printf "\\e[31m%s\\e[0m\\n" "$1" 1>&2
	else
		printf "ERROR: %s\\n" "$1" 1>&2
	fi
	[ -n "$2" ] && exit "${2:-1}"
}
has() {
	# Parse out all arguments and try to find them in path
	# If an argument cannot be found, set _return and fail
	for prog in "$@"; do
		if ! command -v "$prog" > /dev/null 2>&1; then
			_return="$prog"
			return 1
		fi
	done
	return 0
}

# Core program functions
printhelp() {
	cat << EOF
Usage: $_name [OPTION]... [LEVEL]
Use xdotool on a modded Minecraft instance holding an Ars Magica 2 Journal
to give the player enough XP to reach the specified level.

  -h			Print this help text

Copyright (c) 2019 rehashedsalt@cock.li
Licensed under the MIT license
EOF
}
givelevels() {
	# Give a player $1 levels through xdotool
	[ -z "$1" ] && return 1
	log "Poof, you now have $1 levels"
	return 0
	xdotool click\
		--delay 0.1\
		--repeat "TODO"\
		3
}

# Main
main() {
	while getopts ":h" opt; do
		case $opt in
			h)
				_opthelp=1
				;;
			:)
				error "Option requires argument: -$OPTARG" 2
				;;
			*)
				error "Invalid option: -$OPTARG" 2
				;;
		esac
	done
	# Shift over to the arguments
	shift $((OPTIND - 1))
	for arg in "$@"; do
		if ! [ "$arg" -eq "$arg" ] 2>/dev/null; then
			error "Argument not an integer: $arg" 2
		fi
		if ! [ "$arg" -gt 0 ]; then
			error "Argument not greater than 0: $arg" 2
		fi
		if [ -z "$_level" ]; then
			_level="$arg"
		else
			error "Too many arguments: $arg" 2
		fi
	done
	[ -n "$_opthelp" ] && printhelp && exit 0
	[ -z "$_level" ] && error "Program requires argument" 2
	givelevels "$_level"
}

main "$@"