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



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

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



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

# v1.2 - 2014-09-24: temp file bug corrected / check if local file exist
# v1.1 - 2014-09-14: test_dep bug corrected
# v1.0 - 2014-09-14: git dependency check replaced by wget check (bug) / test_dep function improved / remove comments in list file / check for http path / remove spaces in path / checksum loop corrected
# 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 {
    which $1 &> /dev/null
    if [[ $? != 0 ]]
    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 (path1 ; path2). The remote path must be http path.
                    Comments beginning by # are allowed anywhere.

    -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 wget



#==========================#
# 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

# Temporary list
mydate=$(date +%N)
tmp_list="/tmp/$(basename $list)-$mydate"



#============#
# 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


# Remove comments from list file
sed "/^\s*#/d;s/\s*#.*$//" "$list" > "$tmp_list"


# Synchronization
while read line
do

    # Get paths
    mysrc=$(echo "$line" | cut -d ";" -f 1 | sed -e "s/^ *//" -e "s/ *$//")
    mydst=$(echo "$line" | cut -d ";" -f 2 | sed -e "s/^ *//" -e "s/ *$//")

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

    # Check if destination file exists
    if [[ ! -e "$mydst" ]]
    then
        warning "${mydst##*/}: Local file does not exist. Skipping..."
        continue
    fi


    # Check if remote path is http
    if [[ ! $(echo "$mysrc" | grep -i "^http") ]]
    then
        warning "${mydst##*/}: Remote path is not http address. Skipping..."
        continue
    fi

    # Download file
    wget --no-check-certificate -O "$mydst_tmp" "$mysrc" &> /dev/null

    # 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)
        mydst_tmp_md=$(md5sum "$mydst_tmp" | cut -d " " -f 1)
        mydst_md=$(md5sum "$mydst" | cut -d " " -f 1)
        if [[ "$mydst_tmp_md" != "$mydst_md" ]]
        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 < "$tmp_list"


# Remove temporary list
rm "$tmp_list"


exit 0
