#!/bin/bash
###############################################################################
# remotemirror.bash
# Chris Cera
###############################################################################
# 1. hardcoded to ssh to queen
# 2. tar.gz the cs172 public_html dir
# 3. sftp locally and copy to cwd
# 4. un-tar in /tmp
# 5. re-zip and copy back to cwd
# 6. remove tarball
###############################################################################
# BUGS

# MAKES A ZIP ARCHIVE STARTING AT HOME??
###############################################################################
# gzip, zip, and tar are required on your system
# ssh required to get on remote system, requires TWO prompts for password
###############################################################################
# zip was not installed on queen, thus a conversion is necessary, locally
###############################################################################
# Why didn't you use wget instead off ssh'ing in, then sftp'ing back?
# 
# Because wget works on references to other url's at a specified depth.  Not
# everything on the website is actually referenced, but we need it.  Until I
# find a program with documentation on something better, this will do.
###############################################################################

stamp=`date +%Y%m%d`
archive="/usr/local/bin/tar cvf"
gzip="/usr/local/bin/gzip -f -9"
MV="/bin/mv"
rm="/bin/rm"
old_pwd=`pwd`

course=cs172
account=uccera@queen.mcs.drexel.edu

targetdir=~mcs172/public_html/
targetsuff=Sp01
target=$targetdir$targetsuff

homedir=~uccera/
relqueendir=bak/
absqueendir=$homedir$relqueendir
tmp=/tmp/cs172_backup/

prefix=$course.queen.$stamp.html
archivefile=$prefix.tar
gzipfile=$prefix.tar.gz
zipfile=$prefix.zip

echo "archiving $account:$target ..." && echo -n "    "
ssh $account "cd $targetdir &&
    $archive $absqueendir$archivefile $targetsuff >& /dev/null && 
    $gzip $absqueendir$archivefile"
echo " DONE" &&

echo "copying to $relqueendir$gzipfile to $old_pwd ..." && echo -n "    "
scp $account:$relqueendir$gzipfile .
echo " DONE" &&

if [ ! -d $tmp ]; then
    echo "$tmp does not exist, creating ..."
    mkdir $tmp
fi

cd $tmp && 
    echo -n "unzipping $old_pwd/$gzipfile ..." &&
    tar xvfz $old_pwd/$gzipfile >& /dev/null &&
    echo " DONE" &&

    echo -n "zipping ..." &&
    zip -r $zipfile * >& /dev/null &&
    echo " DONE" &&

    echo mv $zipfile $old_pwd THIS DIES, GRAB THE ZIPFILE IN $tmp$zipfile &&
    $MV $zipfile $old_cwd &&
    $rm $old_pwd/$gzipfile
