#!/bin/sh

GITEA_URL="http://git.konsthol.eu:3333"

USERNAME="konsthol"

#MENU="rofi -theme-str 'window {width: 400px; height: 200px;}' -dmenu -i -p 'Repo to delete'"
MENU="rofi -dmenu -i -p repoToDelete"
[[ -n "$SSH_TTY" ]] && MENU="fzf -i --prompt=repoToDelete"

NAME="${0##*/}"

function usage() {

cat <<EOF

 USAGE: $NAME [OPTIONS]

 OPTIONS:

     -h,--help          Display this message

     -c,--create        Create a reposiroty
     
     -i,--instant       Create a reposiroty in current folder with random commit message

     -d,--delete        Delete a reposority

     -l,--list          List repositories

EOF

}

function createRepo() {

curl -X POST \
"$GITEA_URL/api/v1/user/repos?access_token=$(pass SelfHosted/giteaTokenForKonsthol)" \
	-H "accept:application/json" \
	-H "Content-Type: application/json" \
	-d "{
		\"auto_init\": false,
		\"description\": \"$2\",
		\"gitignores\": \"\",
		\"issue_labels\": \"\",
		\"license\": \"\",
		\"name\": \"$1\",
		\"private\": false,
		\"readme\": \"\"
	}"

}

function deleteRepo() {

curl -X DELETE \
"$GITEA_URL/api/v1/repos/$USERNAME/$1?access_token=$(pass SelfHosted/giteaTokenForKonsthol)" \
	-H "accept:application/json"

}

function listRepos {

RESPONSE=$(curl -s -X GET \
"$GITEA_URL/api/v1/users/$USERNAME/repos?access_token=$(pass SelfHosted/giteaTokenForKonsthol)" \
        -H "accept:application/json" \
        -H "Content-Type: application/json" \
	-d "{
        	\"page\": \"5\",
	        \"limit\": \"5\"
	}")

echo "$RESPONSE" | jq | grep "full_name\": \"$USERNAME" | awk -F/ '{print $2}' | sed 's/"//g' | sed 's/,//g'

}

if (( $# == 0 )); then
	usage
else
	for arg in "$@"; do
		case $arg in
			-h|--help)
				usage
				;;
			-c|--create)
				read -p "Enter new repo's name (no spaces): " name
				read -p "Enter new repo's description: " description
				createRepo "$name" "$description" | jq
				;;
			-i|--instant)
				read -p "Enter new repo's description: " description
				createRepo "$(basename $PWD)" "$description" | jq
				git init
				git add .
				git commit -m "$(curl -s http://whatthecommit.com/index.txt)"
				git remote add origin $GITEA_URL/$USERNAME/$(basename $PWD)
				git push -u origin master
				;;
			-d|--delete)
				NAME="$(giteaDo -l | $MENU)"
				[[ -n $NAME ]] && deleteRepo "$NAME"
				;;
			-l|--list)
				listRepos
				echo -e ""
				;;
			*)
				printf "\nOption does not exist: %s\n\n" "$arg"
		esac
	done
fi
