#!/usr/bin/env bash

######################################################
#
# https://wiki.bash-hackers.org/howto/getopts_tutorial
# https://sookocheff.com/post/bash/parsing-bash-script-arguments-with-shopts/
######################################################

function help() {
	echo -e "EdX Course Backup Script\n"
  echo -e "Usage: $0 [PARAMETERS]..."
  echo -e "\nParameters:"

	echo -e "\t-o absolute folder path where backup will dumped"
	exit 1;
}

#Check the shell
if [ -z "$BASH_VERSION" ]; then
    echo -e "Error: this script requires the BASH shell!"
    exit 1
fi

OUTPUT_PATH=""

# In Silent Mode, that is disable the verbose error handling by preceding the whole option string with a colon (:)
while getopts ':ho:' opt
do
	case $opt in
		o)
			OUTPUT_PATH=$OPTARG
		;;

		h)
			help
		;;

		\?) # In Silent Mode, opt is set to ? if invalid option passed and $OPTARG is set to the (invalid) option character
			echo "Invalid option: -$OPTARG" >&2
		;;

		:) # In Silent Mode, opt is set to : if required argument not found and $OPTARG contains the option-character in question
			echo "Option -$OPTARG requires an argument." >&2
		;;
	esac
done

if ((OPTIND == 1))
then
    echo "No options specified"
    help
    exit 1
fi

if [ ! -d $OUTPUT_PATH ]; then
  echo "Output path $OUTPUT_PATH doesn't exist, so creating it"
  mkdir -p $OUTPUT_PATH
fi

COURSE_BACKUP_NAME="edx_course_backup_at_$(date +%F)"
COURSE_OUT_PATH=$OUTPUT_PATH/$COURSE_BACKUP_NAME
mkdir -p $COURSE_OUT_PATH
echo "COURSE_OUT_PATH is $COURSE_OUT_PATH"

echo "Taking all courses backup....."
/data/open-edx/apps/edx/bin/python.edxapp \
  /data/open-edx/apps/edx/edx-platform/manage.py cms \
  --settings bitnami \
  export_all_courses $COURSE_OUT_PATH
echo "Done."

echo "Compressing the backup..."
tar fcz ${COURSE_OUT_PATH}.tar.gz -C /$OUTPUT_PATH $COURSE_BACKUP_NAME
echo "Done."

echo "Removing the uncompressed one $COURSE_OUT_PATH"
rm -rf $COURSE_OUT_PATH
echo "Done."