#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail

BACKUP_DIR=""
SOURCE_DIR_UPLOAD=""
SOURCE_DIR_WEBAPPS=""
BACKUP_COMPRESS_DIR=""
BACKUP_UPLOAD_PATH=""
BACKUP_WEBAPPS_PATH=""
UPLOAD_TARGET=""
WEBAPPS_TARGET=""
LATEST_UPLOAD_LINK=""
LATEST_WEBAPPS_LINK=""
SOURCE_DIR_UPLOAD="upload to path"
SOURCE_DIR_WEBAPPS="webapp to path"
BACKUP_DIR="backup to path"
BACKUP_UPLOAD_PATH="${BACKUP_DIR}/upload/source"
BACKUP_WEBAPPS_PATH="${BACKUP_DIR}/webapps/source"
BACKUP_COMPRESS_DIR="${BACKUP_DIR}/compress"
UPLOAD_TARGET="${BACKUP_COMPRESS_DIR}/upload.tar.gz"
WEBAPPS_TARGET="${BACKUP_COMPRESS_DIR}/webapps.tar.gz"
LATEST_UPLOAD_LINK="${BACKUP_DIR}/upload/latest"
LATEST_WEBAPPS_LINK="${BACKUP_DIR}/webapps/latest"

if [ ! -d "${BACKUP_DIR}" ]
then
	mkdir -p "${BACKUP_DIR}"
fi
if [ ! -d "${BACKUP_UPLOAD_PATH}" ]
then
	mkdir -p "${BACKUP_UPLOAD_PATH}"
fi
if [ ! -d "${BACKUP_WEBAPPS_PATH}" ]
then
	mkdir -p "${BACKUP_WEBAPPS_PATH}"
fi
if [ ! -d "${BACKUP_COMPRESS_DIR}" ]
then
	mkdir -p "${BACKUP_COMPRESS_DIR}"
fi

rsync -av --delete \
  "${SOURCE_DIR_UPLOAD}/" \
  --link-dest "${LATEST_UPLOAD_LINK}" \
  --exclude=".cache" \
  "${BACKUP_UPLOAD_PATH}"

rsync -av --delete \
  "${SOURCE_DIR_WEBAPPS}/" \
  --link-dest "${LATEST_WEBAPPS_LINK}" \
  --exclude=".cache" \
  "${BACKUP_WEBAPPS_PATH}"

rm -rf "${LATEST_UPLOAD_LINK}"
rm -rf "${UPLOAD_TARGET}"
rm -rf "${LATEST_WEBAPPS_LINK}"
rm -rf "${WEBAPPS_TARGET}"
ln -s "${BACKUP_UPLOAD_PATH}" "${LATEST_UPLOAD_LINK}"
ln -s "${BACKUP_WEBAPPS_PATH}" "${LATEST_WEBAPPS_LINK}"
tar -cf "${UPLOAD_TARGET}" "${BACKUP_UPLOAD_PATH}"
tar -cf "${WEBAPPS_TARGET}" "${BACKUP_WEBAPPS_PATH}"
