#!/bin/bash
##################################################
# NAME
#   sync-math - Script to sync math notes to web
#   (based on backup-script)

# SYNOPSIS
#   sync-math [OPTION]...

# Takes two options:
# -q = quiet
#  for use by cron
# -c = clean
#  deletes backup files, and removes files in the backup that
#  don't exist anymore (i.e., have been deleted or moved since)

##################################################
# Code

# use keychain for authentication
HOST=virgil
source ~/.tmp/keychain-$HOST-sh > /dev/null

#### First, parse options
# Default options
#unset CLEAN
#unset QUIET

while getopts "cq" flag
do
  if [ "$flag" == "c" ]
    then
      CLEAN="TRUE"
  elif [ "$flag" == "q" ]
    then
      QUIET="TRUE"
  fi
done

##################################################
# clean up old backups

if [ -n "$CLEAN" ]
  then if ! [ -n "$QUIET" ]
    then
      echo "Cleaning up old backup files"
      cd ~/book/
      ~/usr/bin/clean
  else
      cd ~/book/
      ~/usr/bin/clean &> /dev/null
  fi
fi

##################################################
# Set rsync options, given parameters

if [ -n "$QUIET" ]
  then
    OPTIONS="--quiet"
  else
    OPTIONS="--verbose --progress"
fi

if [ -n "$CLEAN" ]
  then
    OPTIONS="$OPTIONS --delete"
fi

# Default parameters
# Archive, but don't keep permissions: everything world-readable
OPTIONS="$OPTIONS --archive --no-p --no-g --chmod=ugo=rwX"

##################################################
# Actual backing up

REMOTE_USER_HOST=nbarth@cookie.dreamhost.com
REMOTE_BASE_DIR=/home/nbarth/nbarth.net/notes
##################################################
# All but output
SOURCE_DIR=/home/nbarth/book/ # The trailing / is important
DEST_DIR=$REMOTE_USER_HOST:$REMOTE_BASE_DIR/src
  # the lack of trailing / is important

rsync --exclude "OUT"\
      --exclude "index.html"\
  $OPTIONS "$SOURCE_DIR" "$DEST_DIR"
# Don't sync output files

##################################################
# Sync output here
SOURCE_DIR=/home/nbarth/book/OUT/ # The trailing / is important
DEST_DIR=$REMOTE_USER_HOST:$REMOTE_BASE_DIR/out
  # the lack of trailing / is important

rsync $OPTIONS "$SOURCE_DIR" "$DEST_DIR"
##################################################
# index.html only

SOURCE=/home/nbarth/book/index.html
DEST=$REMOTE_USER_HOST:$REMOTE_BASE_DIR/index.html

rsync $OPTIONS "$SOURCE" "$DEST"

##################################################
# Fix permissions
# Off for now -- seeing if syncing works ok

#if ! [ -n "$QUIET" ]
#  then
#    echo "Fixing permissions"
#fi

# Make everything readable
#ssh $REMOTE_USER_HOST "chmod a+r -R ~/nbarth.net/book/"
# directories too!
#ssh $REMOTE_USER_HOST 'for i in `find ~/nbarth.net/book/ -type d` ; do chmod +x "$i" ; done'
