#!/bin/sh
# stagit setup helper - developed by acidevegas (https://git.acid.vegas/stagit)
# debian : sudo apt-get install libgit2-1.1  libmd4c*
# arch   : sudo pacman -S libgit2 md4c

URL="git.acid.vegas"
PROTO="https"
CLONE_URL="git://$URL"
COMMIT_LIMIT=100
HTML_DIR="/srv/http"
REPOS_DIR="/srv/git"

prepair() {
	[ -d $HTML_DIR ] && rm -rf $HTML_DIR/*
	mkdir -p $HTML_DIR/assets
	echo "[~] populating custom assets..."
	cp acidvegas.png favicon.png logo.png mostdangerous.png style.css $HTML_DIR/assets
}

make_index() {
	echo "[~] creating 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
}

make_repo() {
	REPO=$(basename "$(echo "$1" | sed 's/\.git$//')")
	if [ -f $1/description ]; then
		if [ "$(cat $1/description)" = "Unnamed repository; edit this file 'description' to name the repository." ]; then
			read -p "description for '$REPO':" desc
			echo "$desc" > $1/description
			echo "[+] updated default 'description' file for '$REPO'"
		fi
	else
		read -p "description for '$REPO':" desc
		echo "$desc" > $1/description
		echo "[+] added missing 'description' file for '$REPO'"
	fi
	if [ ! -f $1/url ]; then
        echo "$CLONE_URL/$REPO.git" > $1/url
		echo "[+] added missing 'url' file for '$REPO'"
	fi
	echo "[~] processing '$REPO' repository..."
	mkdir -p $HTML_DIR/$REPO && cd $HTML_DIR/$REPO && stagit -l $COMMIT_LIMIT -u "$PROTO://$URL/$REPO" $1
	ln -sf log.html index.html
	git --git-dir $1 archive --format=tar.gz -o "$HTML_DIR/$REPO/archive.tar.gz" --prefix="$REPO/" HEAD
}

make_all_repos() {
	for dir in $(find $REPOS_DIR -type d -name "*.git" | sort); do
		make_repo $dir
	done
}

# Main
prepair
make_all_repos
make_index