#!/bin/bash
# Simple script to update archive of web files at my PC mashine.
# The archive is then could be backuped. It also makes an attempt to 
# copy it onto hosting mashine.
# (c) Light Olli <olli@digger.org.ru>, License is current GNU GPL.

# The 1st & required check - vars are being build with this utility.
if [ -z `which which` ]; then
    echo "Existing of the 'which' utility is a must for $0. Sorry."
    exit 1
fi

## variables.

# utils used
CP=`which cp`
RM=`which rm`
CHOWN=`which chown`
TAR=`which tar`
FIND=`which find`
SCP=`which scp`
SSH=`which ssh`

# permissions for directories
dmode=755
# permissions for directories
fmode=644
pubhtml=public_html
newarch=public_html.tar
# where the copy of the site arhive should be saved also.
copy2dir=$HOME/Records.merged/pvt/web-sites
dir=$HOME
hosting=town.mtcm.ru
hostinguser=olli
hostingdir="/home/$hostinguser"
user=olli
## script work start.

# checks
if [ -z $CP ]; then echo "'cp' is required. Sorry."; exit 1; fi 
if [ -z $RM ]; then echo "'rm' is required. Sorry."; exit 1; fi 
if [ -z $CHOWN ]; then echo "'chown' is required. Sorry."; exit 1; fi 
if [ -z $TAR ]; then echo "'tar' is required. Sorry."; exit 1; fi 
if [ -z $FIND ]; then echo "'find' is required. Sorry."; exit 1; fi 
if [ -z $SCP ]; then echo "'scp' is required. Sorry."; exit 1; fi 
if [ -z $SSH ]; then echo "'ssh' is required. Sorry."; exit 1; fi 

# real work
echo "This script assumes that your public_html directory is $dir/$pubhtml,"
echo "It also assumes that its new version is in $dir/$newarch file."
echo "Backups of old $dir/$newarch are made in format file.yyyy.mm.dd,"
echo "old backups from same date are overwriten silently."
echo "Edit $0 to change this beheviour."
echo "press <Enter> to continue or ^C to quit"
read wait
cd $dir
echo "Setting permissions to 644 & 755 for files & dirs.."
$FIND $pubhtml -type f -exec chmod $fmode {} \; ; find $pubhtml -type d -exec chmod $dmode {} \;
echo "Setting owner & group for $pubhtml recursively"
$CHOWN -R $user. $pubhtml
echo "Creating a copy.."
$CP -f $newarch $newarch.`date +%Y.%m.%d`
echo "Removing old file.."
$RM -f $newarch
echo "Archiving files.."
$TAR cf $newarch $pubhtml
echo "Copying $newarch to $copy2dir.."
$CP -f $newarch $copy2dir
echo "starting scp $newarch $hostinguser@$hosting:$hostingdir"
$SCP $newarch $hostinguser@$hosting:$hostingdir
echo "starting interactive connection.."
echo "(run public_html_renew.sh at the remote end to renew files from created archive)"
$SSH $hostinguser@$hosting
