#!/bin/bash

# git2gz v0.1  GPL

if [ -z "$1" ]
then
        echo "No argument given."
        echo "Usage: `basename $0` git://git-domain.com/example/example.git"
        exit 1
fi


gitx=$1

# prÃ¼fen ob notwendige Programme vorhanden sind

which awk >/dev/null 2>&1

if [ $? -ne 0 ]
then
        echo "[awk] is not installed on your system!"
        exit 1
fi

which git >/dev/null 2>&1

if [ $? -ne 0 ]
then
        echo "[git] is not installed on your system!"
        exit 1
fi


# domain name extrahieren und prÃ¼fen ob erreichbar

git_domain=`echo $gitx  | awk -v FS="/" '{print $3}'`

ping -c 1 $git_domain >/dev/null 2>&1

if [ $? -ne 0 ]
then
        echo "The Domain [`echo $git_domain`] ist not available"
        echo "or the network is not reachable"
        exit 2
fi

# Temporary ordner prÃ¼fem
if [ -d "/tmp" -a -w "/tmp" ]
then
        dtmp="/tmp/"
else
        if [ ! -d ~/tmp ]
        then
                mkdir ~/tmp
                if [ $? -ne 0 ]
                then
                        echo "Create the [tmp] failed!"
                        exit 1
                fi
        fi
        dtmp="~/tmp/"
fi
s1=${gitx##*/}
s2=${s1%%.*}

now=`date +'_%Y%m%d'`

gitn="$s2$now"

gitcdir="$dtmp$gitn"

if [ ! -d $gitcdir ]
then
        mkdir $gitcdir
fi

git clone $gitx $gitcdir
if [ $? -ne 0 ]
then
        echo "[git] could not finish its work!"
        exit 1
else

gzn=$gitn

n=0

while [  -e $gzn.tar.gz ]
  do
       let ++n
        gzn="$gitn($n)"
done

        tar czfv $gzn.tar.gz $gitcdir  >/dev/null 2>&1
        if [ $? -ne 0 ]
        then
                echo "directory could not be packed!"
                exit 1
        fi
fi
rm -Rf $gitcdir
if [ $? -ne 0 ]
then
        echo "[tmp] directory could not be deleted!"
        exit 1
fi

du -h  $gzn.tar.gz
