#!/bin/sh
# git-shell-commands helper for stagit - developed by acidvegas (https://git.acid.vegas/stagit)

if [ "$#" -ne 2 ]; then
	echo "invalid arguments (use -c or -d)"
	exit 1
elif [ "$1" = '-c' ]; then
	if [ -d "$2.git" ]; then
		echo "repository already exists"
		exit 1
	else if [ ! -f post-receive ]; then
		echo "missing post-receive script"
		exit 1
	fi
	mkdir "$2.git"
	git init --bare "$2.git"
	touch "$2.git/git-daemon-export-ok"
	ln /srv/git/git-shell-commands/post-receive "$2.git/hooks/post-receive" 
	echo "https://git.acid.vegas/$2.git" > "$2.git/url"
	echo "Description for '$2' repository:"
	read desc
	echo "$desc" > "$2.git/description"
	echo "[~] recreating index..."
    args=""
    for category in $(cat /srv/git/*/owner | xargs -n1 | sort -u | xargs); do
        echo "[~] indexing '$category' repositories..."
		REPOS=$(grep -rl "$category" /srv/git/*/owner | xargs -I{} dirname {} | sort -f | tr '\n' ' ')
        args="$args -c \"$category\" $REPOS"
    done
    echo "$args" | xargs stagit-index > $HTML_DIR/index.html
elif [ "$1" = '-d' ]; then
	if [ ! -d "$2.git" ]; then
		echo "repository does not exist"
		exit 1
	fi
	rm -rf "$2.git"
else
	echo "invalid arguments (use -c or -d)"
	exit 1
fi