#!/bin/bash
# Synchronizer script of static Wordpress files to Amazon S3.
#    by W-Mark Kubacki; wmark@hurrikane.de
#    http://mark.ossdl.de/
#
# Utilizes s3cmd, which can be found here:
#    http://s3tools.org/s3cmd
#
# Licensed under RPL for private and academia use,
# and only so for commercial use and blogs with advertisements if
# a paypal donation is made to the author.
#
# version 2009-09-11-r2
# version 2010-01-29
#

# the bucket files will be synced with; e.g. s3://my-blog/
BUCKET=s3://mark-blog/
# temporary directory for CSS and JS file structure, will be created
TMPDIR=/tmp/mark-blog

# all files except JS and CSS
sync_files() {
	for DIR in ./; do
		s3cmd sync --exclude 'wp-admin/**' --exclude 'wp-content/cache/**' --exclude '**.svn**' \
		--exclude '*.php' --exclude '*.js' --exclude '*.css' --exclude '.htaccess' \
		--exclude '*.orig' \
		--acl-public --guess-mime-type --add-header=Cache-Control:max-age=604800 \
		--no-preserve --recursive "${DIR}" "${BUCKET}"
	done
}

# JS and CSS files; being compressed if necessary, then synchronized
sync_js() {
	test -e $TMPDIR && rm -r $TMPDIR
	for F in $(find -type f -readable -name '*.js' -o -name '*.css' ! -path '**.svn**' ! -path 'wp-content/cache/**' | grep -v 'wp-admin/' | cut -b 3-); do
		mkdir -p "${TMPDIR}/${F%/*}"
		file "${F}" | grep -q gzip \
		&& cp -a "${F}" "${TMPDIR}/${F}" \
		|| gzip -9 -c "${F}" > "${TMPDIR}/${F}"
	done
	cd $TMPDIR
		s3cmd sync --exclude '*.*' --include '*.js' --include '*.css' \
		--add-header=Content-Encoding:gzip \
		--acl-public --guess-mime-type --add-header="Cache-Control:max-age=604800, public" \
		--no-preserve --recursive ./ "${BUCKET}"
	cd -
	test -e $TMPDIR && rm -r $TMPDIR
}

case "$1" in
	js)
		echo "Will sync JS and CSS..."
		sync_js
		;;
	data)
		echo "Will sync data only..."
		sync_files
		;;
	*)
		echo "Usage: $0 [js|data]"
		;;
esac

exit 0
