#!/usr/bin/env zsh

# Author: Yann Esposito
#   Mail: yann.esposito@gmail.com
# Synchronize with "mobileMe" iDisk account.

mobileMeUser="firstname.lastname"
siteName="siteName"

# Depending of my hostname the 
if [[ $(hostname) == 'ubuntu' ]]; then
    iDisk='/mnt/iDisk'
else
    iDisk="/Volumes/$mobileMeUser"
fi

root=$HOME/Sites/$siteName
destRep=$iDisk/Web/Sites/$siteName

[[ ! -d $root ]] && { 
    print -- "$root does not exist ; please verify the configuration ($0)" >&2; 
    exit 1 
}

[[ ! -d $destRep ]] && { 
    print -- "$destRep does not exist, please mount the filesystem" >&2; 
    exit 1 
}

if [[ $1 == '-h' ]]; then
    print -- "usage: $0:h [-h|-a|-s]"
    print -- "  -a sychronize primary index"
    print -- "  -h show this help"
    print -- "  -s only swap directories"
fi

if [[ $1 == '-a' ]]; then
    print -- "Index synchronisation (${destRep:h})"
    rsync -av $root/index.html ${destRep:h}/index.html
fi

print -- "Root = $root"
print -- "Dest = $destRep"

if [[ ! $1 = '-s' ]]; then
    [[ ! -d $destRep.tmp ]] && mkdir $destRep.tmp
    print -P -- "%B[Sync => tmp]%b"
    result=1
    essai=1
    while (( $result > 0 )); do
        rsync -arv $root/Scratch/ $destRep.tmp
        result=$?
        if (( $result > 0 )); then
            print -P -- "%Brsync failed%b (try n°$essai)" >&2
        fi
        ((essai++))
    done
fi

# SWAP
print -P -- "%B[Directory Swap (tmp <=> target)]%b"
essai=1
while [[ -e $destRep.old ]]; do
    print -n -- "remove $destRep.old"
    if ((essai>1)); then 
        print " (try n°$essai)"
    else
        print
    fi
    ((essai++))
    \rm -rf $destRep.old
done

print -- "  renommage du repertoire sandard vers le .old"
essai=1
while [[ -e $destRep ]]; do
    mv $destRep $destRep.old 
    (($?)) && print -- "Failed to rename (try n°$essai)" >&2
    ((essai++))
done

print -- "  renaming folder tmp (new) to the standard one"
print -P -- "  %BThe WebSite isn't working%b $(date)"
essai=1
while [[ ! -e $destRep ]]; do
    mv $destRep.tmp $destRep
    (($?)) && print -P -- "%B[WebSite not working]%b(try n°$essai) Failed to rename (mv $destRep.tmp $destRep)" >&2
    ((essai++))
done

print -P -- "\t===\t%BWEBSITE SHOULD WORK NOW%b\t==="

print -- "  rename old folder to tmp folder"
essai=1
while [[ ! -e $destRep ]]; do
    mv $destRep.old $destRep.tmp
    (($?)) && print -P -- "Failed to rename n°$essai" >&2
    ((essai++))
done

print -P -- "  Publish terminated"
