#!/bin/sh

help()
  {
    echo "Usage: ./copy_dir.sh /some/dir/name /mnt/some/where"
  }

if [ $(echo $* | wc -w) -le 0 ]; then
  echo "Error: No arguments!"
  help
  exit 1
fi

for i in $*; do
  if [ ! -d $i ]; then
    echo "Error: $i is not a directory!"
    help
    exit 2
  fi
done

SOURCE_PATH="$1"
if [ $(echo ${SOURCE_PATH} | egrep -c '/$') -ne 0 ]; then
  SOURCE_PATH=$(echo ${SOURCE_PATH} | sed 's/\/$//')
fi
if [ $(echo ${SOURCE_PATH} | egrep -c '/') -ne 0 ]; then
  SOURCE_BASE=$(echo ${SOURCE_PATH} | awk -F '/' '{for(i=2;i!=NF;i++){printf "/%s", $i}; printf "\n"}')
else
  SOURCE_BASE=$(pwd)
fi
SOURCE_DIR=$(echo ${SOURCE_PATH} | awk -F '/' '{print $NF}')
DEST_PATH="$2"
if [ $(echo ${DEST_PATH} | egrep -c '/$') -ne 0 ]; then
  DEST_PATH=$(echo ${DEST_PATH} | sed 's/\/$//')
fi
DEST_DIR="${DEST_PATH}/${SOURCE_DIR}"

run_copy_job() {
  START=$(date +%s)
  while [ $(( $(date +%s) - 86400 )) -lt $START ]; do
    EXIT_CODE="0"
    if [ ${EXIT_CODE} -le 0 ]; then
      echo "Moving copy materials out to testbake."
      if [ -d ${DEST_DIR} ]; then
        rm -rf ${DEST_DIR}
      fi
      cp -rf ${SOURCE_PATH} ${DEST_PATH}/ 2>/dev/null
      if [ $? -le 0 ]; then
        echo "Moving copy materials back from testbake."
        if [ -d ${SOURCE_PATH} ]; then
          rm -rf ${SOURCE_PATH}
        fi
        cp -rf ${DEST_DIR} ${SOURCE_BASE}/ 2>/dev/null
        if [ $? -le 0 ]; then
          EXIT_CODE="0"
        else
          EXIT_CODE="1"
          break
        fi
      else
        EXIT_CODE="1"
        break
      fi
    fi
  done

  echo "Exit code was \"${EXIT_CODE}\"."
}

echo "The source base path is:      ${SOURCE_BASE}"
echo "The source base directory is: ${SOURCE_DIR}"
echo "The destination base path is: ${DEST_PATH}"
echo ""
echo "This script will run for the next 24 hours."

while true; do
  read -p "Do you wish to continue? " OPTION
  case ${OPTION} in
    [Yy]|[Yy][Ee][Ss])
      run_copy_job
      break
    ;;
    [Nn]|[Nn][Oo])
      exit 3
    ;;
    *)
      echo "Please answer yes or no."
    ;;
  esac
done
