#!/bin/bash

check_repo(){
	if [ -z "$SELECTED_REPO" ]; then
		echo "$0: error: you must first use the select command to pick a repo to operate on" >&2
		exit 1
	else
		echo "Operating on: $SELECTED_REPO"
	fi
}
usage_and_exit(){
	exec >&2
	echo "$0: error: incorrect syntax"
	echo "Usage: $parentcmd $cmd [--global|--local] list"
	echo "       $parentcmd $cmd [--global|--local] <get|unset> <key>"
	echo "       $parentcmd $cmd [--global|--local] set <key> <value>"
	exit 1
}

cmd="$(basename "$0")"
is_global=""
mode=""
while [ -n "$1" ]; do
	if [ "$1" = "--global" ]; then
		is_global="--global"
	elif [ "$1" = "--local" ]; then
		is_global="--local"
	elif [ "$1" = "unset" ]; then
		mode="unset"
	elif [ "$1" = "get" ]; then
		mode="get"
	elif [ "$1" = "set" ]; then
		mode="set"
	elif [ "$1" = "list" ]; then
		mode="list"
	else
		break
	fi
	shift
done

if [ "$mode" = "set" ]; then
	if [ $# -ne 2 ]; then
		usage_and_exit
	fi
elif [ "$mode" = "list" ]; then
	if [ $# -ne 0 ]; then
		usage_and_exit
	fi
	git -C "$SELECTED_REPO" config list $is_global
	exit 0
else
	if [ $# -ne 1 ]; then
		usage_and_exit
	fi
fi

if [ "$is_global" != "--global" ]; then
	check_repo
fi

key="$1"
value="$2"

whitelist_keys=(
	hooks.*
	init.defaultObjectFormat
	init.defaultRefFormat
	cgit.{owner,section,desc,homepage,hide,defbranch,branch-sort,readme}
	cgit.{logo,logo-link,extra-head-content,enable-remote-branches}
)

for whitelist_key in "${whitelist_keys[@]}"; do
	if [[ $key == $whitelist_key ]]; then
		if [ "$mode" = "set" ]; then
			git -C "$SELECTED_REPO" config $is_global $mode -- "$key" "$value"
		else
			git -C "$SELECTED_REPO" config $is_global $mode -- "$key"
		fi
		exit
	fi
done

echo "Key not allowed: $key" >&2
exit 2
