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



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

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



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

# v0.1 - 2014-09-23: dry-run option added / no check certifcate option added for wget
# 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 -d|--dry-run -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.

    -d, --dry-run   Run the synchronization but print a message instead of updating the files. 

    -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 ;;
        -d|--dry-run ) dry=1 ; shift ;;
        -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 --no-check-certificate -O "$mydst_tmp" "$mysrc"

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

done < "$list"


exit 0