#!/bin/bash
# Title: git-repo-creator.sh
# Version: 0.1
# Author: Frédéric CHEVALIER <fcheval@txbiomedgenetics.org>
# Created in: 2014-08-31
# Modified in: 2014-09-01
# Licence : GPL v3



#======#
# Aims #
#======#

aim="Create a git repository locally and remotely on a given server using ssh."



#==========#
# Versions #
#==========#

# v0.1 - 2014-09-01: default value for -d using structure of -r added / if remote repository exist, skip instead of interrupt the script / addition of missing part of initialisation step when done for the first time / bug correction in the reinitialisation of remote path
# v0.0 - 2014-08-31: creation



#===========#
# Functions #
#===========#

# Dependency test
function test_dep {
    if [[ ! $(which $1) ]]
    then
        error "Package $1 is needed. Exiting..." 1
    fi
}

# Usage message
function usage {
    echo -e "
    \e[32m${0##*/}\e[00m -r|--rep repository_name -d|--drep remote_repository_name -s|--svr server_name -u|--usr user_name -h|--help

Aim: $aim

Options:
    -r, --rep       name or path of the repository created locally
    -d, --drep      name or path of the repository created on the server [default: value of -r]
    -s, --svr       name of the server
    -u, --usr       user name for server connection
    -h, --help      this message
"
}


# Error message
function error {
    echo -e "\e[31mError:\e[00m $1"
    exit $2
}


# Warning message
function warning {
    echo -e "\e[33mWarning:\e[00m $1"
}



#==============#
# Dependencies #
#==============#

test_dep git



#==========================#
# Declaration of variables #
#==========================#

# Options
while [[ $# -gt 0 ]]
do
    case $1 in
        -r|--rep    ) rep="$2" ; shift 2 ;;
        -d|--drep   ) drep="$2" ; shift 2 ;;
        -s|--svr    ) svr="$2" ; shift 2 ;;
        -u|--usr    ) usr="$2" ; shift 2 ;;
        -h|--help   ) usage ; exit 0 ;;
        *           ) error "Invalid option: $1\n$(usage)\n" 1 ;;
    esac
done


# Check the existence of obligatory options
if [[ -z "$rep" ]]
then
    error "The option -r is required. Exiting...\n$(usage)\n" 1
fi

# Check variable value for remote repository
if [[ -n "$drep" ]]
then
    [[ -z "$svr" ]] && error "Server destination missing. Exiting...\n$(usage)\n" 1
    [[ -z "$usr" ]] && error "Server user missing. Exiting...\n$(usage)\n" 1
elif [[ -n "$svr" ]]
then
    [[ -z "$usr" ]] && error "Server user missing. Exiting...\n$(usage)\n" 1
elif [[ -n "$usr" ]]
then
    [[ -z "$svr" ]] && error "Server destination missing. Exiting...\n$(usage)\n" 1
fi

# Set default value for remote repository
if [[ -n "$usr" && -n "$svr" && -z "$drep" ]]
then
    drep="$rep"
fi



#============#
# Processing #
#============#

# Creation of the distant repository
echo -e "Setting remote repository up... (may take a while)"
if [[ -n "$drep" ]]
then

    # Test of the ssh connection
    ssh -q "$usr"@"$svr" "echo 2>&1" &> /dev/null
    if [[ $? != 0 ]]
    then
        error "Unable to connect to the server $svr. Aborting..." 1
    fi

    # Test of the existance of the distant directory
    ssh -q "$usr"@"$svr" "ls $drep" &> /dev/null
    if [[ $? == 0 ]]
    then
        warning "Remote directory exists already on the server."
        read -p "Skipping? [Y/n] " answer
        if [[ -z "$answer" || "$answer" =~ [YES]|[yes] ]]
        then
            echo "Skipping..."
            skip_flag=1
        fi
    fi
    
    if [[ -z $skip_flag ]]
    then
        # Creation of the local sturcture in /tmp
        git --bare init "/tmp/$drep" &> /dev/null

        # Upload of the structure on the server
        old_pwd="$PWD"
        cd /tmp
        scp -p -r "${drep%%/*}" $usr@$svr: &> /dev/null
        cd "$old_pwd"

        # Removing of the tmp files
        rm -R "/tmp/$drep"
    fi
fi


# Creation of the local directory
echo -e "Setting local repository up..."
mkdir -p "$rep" 2> /dev/null

# Git initialisation
cd "$rep"
if [[ -d .git ]]
then
    warning "This repository have already been initialized."
    read -p "Reinitialisation? [y/N] " answer

    if [[ -z "$answer" || "$answer" =~ [N]|[no] ]]
    then
        echo "Skipping..."
    else
        git init
    fi
else
    git init
fi


# Adding remote destination
if [[ -n "$drep" ]]
then
    echo -e "Adding remote destination in the local repository..."

    if [[ $(git remote | wc -l) -gt 0 ]]
    then
        warning "Remote destination has already been set up for this repository."
        read -p "Reinitialisation? [y/N] " answer

        if [[ -z "$answer" || "$answer" =~ [N]|[no] ]]
        then
            echo "Skipping..."
        else
            git remote remove origin
            git remote origin "$usr@$svr:$drep"
        fi

   else
       git remote add origin "$usr@$svr:$drep"
   fi

fi

exit 0
