#!/bin/bash -e

# Control the application's jobs scheduling service (cron)
CART_NAME=cron
CART_VERSION=1.4
cartridge_type=${CART_NAME}-$CART_VERSION
source "/etc/openshift/node.conf"

# Setup instance directory and control script name.
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util

function print_help() {
    cmd=$(basename "$0")
    echo "Usage: $0 app-name namespace uuid"
    echo "$cmd embedded cron service"

    echo "$0 $@" | logger -p local0.notice -t openshift_origin_cron_$cmd
    exit 1

}  #  End of function  print_help.


function _control_cron_service() {
   [ $# -lt 1 ]  &&  return 1
   super_run_as_user "$CTL_SCRIPT $1"

}  #  End of function  _control_cron_service.


function _enable_cron_service() {
   rm -f "$CRON_INSTANCE_DIR/run/stop_lock"
   _control_cron_service "enable"

}  #  End of function  _enable_cron_service.


function _disable_cron_service() {
   _control_cron_service "disable"
   touch "$CRON_INSTANCE_DIR/run/stop_lock"

}  #  End of function  _disable_cron_service.


function _reenable_cron_service() {
   rm -f "$CRON_INSTANCE_DIR/run/stop_lock"
   _control_cron_service "reenable"

}  #  End of function  _reenable_cron_service.


function _reload_cron_service() {
   :  #  Do nothing.
}  #  End of function  _reload_cron_service.


function _move_cron_service() {
   source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/apache
   source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/network
   
   observe_setup_var_lib_dir "$CRON_INSTANCE_DIR"

}  #  End of function  _move_cron_service.

function _pre_move_cron_service() {
   source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/apache
   source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/network

}  #  End of function  _pre_move_cron_service.

function _post_move_cron_service() {
   source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/apache
   source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/network

}  #  End of function  _post_move_cron_service.

function _status_cron_service() {
    if output=$(run_as_user "$CTL_SCRIPT status" 2>&1)
    then
        status_client_result "$output"
    else
        client_result "Cron is either stopped or inaccessible"
    fi
}  #  End of function  _status_cron_service.


#
# main():
#
# Parse and ensure arguments.
while getopts 'd' OPTION
do
    case $OPTION in
        d) set -x ;;
        ?) print_help ;;
    esac
done

[ $# -eq 3 ] || print_help
setup_basic_hook "$1" $2 $3
import_env_vars

CRON_INSTANCE_DIR=$OPENSHIFT_HOMEDIR/$cartridge_type
CTL_SCRIPT="$CARTRIDGE_BASE_PATH/$cartridge_type/info/bin/app_ctl.sh"

cmd=$(basename "$0")
case "$cmd" in
   status)           _status_cron_service     ;;
   start|enable)     _enable_cron_service     ;;
   stop|disable)     _disable_cron_service    ;;
   restart|reenable) _reenable_cron_service   ;;
   reload)           _reload_cron_service     ;;
   move)             _move_cron_service       ;;
   pre-move)         _pre_move_cron_service   ;;
   post-move)        _post_move_cron_service  ;;
esac
