#!/bin/bash
# Title: git-sync.sh
# Version: 0.0
# Author: Frédéric CHEVALIER <fcheval@txbiomedgenetics.org>
# Created in: 2014-09-03
# Modified in:
# Licence : GPL v3



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

aim="Synchronize files from git server (master branch) on this terminal."



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

# v0.0 - 2014-09-03: 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 -l|--list list -h|--help

Aim: $aim

Options:
    -l, --list      file containing remote path and local path of a file to synchronize.
                    The list file must have a unique path pair per line and each path must
                    be semi-colon separated. The remote path must be http path.

    -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
        -l|--list   ) list="$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 "$list" ]]
then
    error "The option -l is required. Exiting...\n$(usage)\n" 1
fi



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

# Check file list
if [[ $(awk -F ";" "END {print NF}" "$list") != 2 ]]
then
    error "The list file "$list" is malformated. Each path pair must be on unique line and each path must be semi-colon (';') separated." 1
fi


# Synchronization
while read line
do

    # Get paths
    mysrc=$(echo "$line" | cut -d ";" -f 1)
    mydst=$(echo "$line" | cut -d ";" -f 2)

    mydst_tmp="/tmp/${mydst##*/}"

    # Download file
    wget -O "$mydst_tmp" "$mysrc"

    # Check for errors
    if [[ $? != 0 ]]
    then
        warning "${mydst##*/}: An error occur during the downloading. Skipping..."
        continue
    else
        # Compare downloaded file and destination file (update file if need)
        if [[ $(md5sum "$mydst_tmp") -ne $(md5sum "$mydst") ]]
        then
            mv "$mydst_tmp" "$mydst"
        else
            rm "$mydst_tmp"
        fi
    fi

done < "$list"


exit 0