#!/bin/bash -e

# Configures application's jobs scheduling service (cron).

function print_help {
    echo "Usage: $0 app-name namespace uuid"

    echo "$0 $@" | logger -p local0.notice -t openshift_origin_cron_configure
    exit 1
}

while getopts 'd' OPTION
do
    case $OPTION in
        d) set -x
        ;;
        ?) print_help
        ;;
    esac
done


[ $# -eq 3 ] || print_help

cartridge_type="cron-1.4"
source "/etc/openshift/node.conf"
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util

setup_embedded_configure "$1" $2 $3
import_env_vars

disable_cgroups

CRON_INSTANCE_DIR=$OPENSHIFT_HOMEDIR/$cartridge_type

#
# Create the core of the application
#
if [ -d "$CRON_INSTANCE_DIR" ]; then
    client_error "Embedded $cartridge_type already attached to $application"
    exit 132
fi

create_cartridge_instance_dir "$cartridge_type"
pushd "$CRON_INSTANCE_DIR" > /dev/null
mkdir -p log etc data pid run
chmod go-rwx data
popd > /dev/null

#
# Create links to the jobs directory and the run jobs script.
#
ln -s ../app-root/repo/.openshift/cron $CRON_INSTANCE_DIR/jobs
ln -s $CART_INFO_DIR/bin/cron_runjobs.sh $CRON_INSTANCE_DIR/cron_runjobs.sh

#
# Setup Permissions
#
chmod +x "$CRON_INSTANCE_DIR/"*.sh || error "Failed to chmod new application scripts" 122
chown $user_id.$group_id -R "$CRON_INSTANCE_DIR/" || error "Failed to chown new application space.  Please contact support" 123
chown root.root "$CRON_INSTANCE_DIR" "$CRON_INSTANCE_DIR"/*.sh
observe_setup_var_lib_dir "$CRON_INSTANCE_DIR"

#
# Enable job scheduling service (cronjobs).
#
super_run_as_user "$CART_INFO_DIR/bin/app_ctl.sh enable"
sleep 1

frequencies=$(cat $CART_INFO_DIR/configuration/frequencies | tr '\n' ',')

client_result ""
client_result "$cartridge_type added to application ${application}"
client_result ""
client_result "To schedule your scripts to run on a periodic basis, add the scripts to " 
client_result "your application's .openshift/cron/{${frequencies%?}}/"
client_result "directories (and commit and redeploy your application)."
client_result ""
client_result "Example: A script .openshift/cron/hourly/crony added to your application"
client_result "         will be executed once every hour."
client_result "         Similarly, a script .openshift/cron/weekly/chronograph added"
client_result "         to your application will be executed once every week."
client_result ""
enable_cgroups
