#!/bin/bash
source "/etc/openshift/node.conf"
source "/etc/rc.d/init.d/functions"
source "/usr/lib/openshift/cartridge_sdk/bash/sdk"

# Constants.
DOP=5  # Degree of Parallelism.


CART_DIRNAME="cron"

function usage() {
   echo "Usage: $0 {run | run-user <uid>} <frequency>"
}

function openshift_origin_users() {
    grep ":${GEAR_GECOS}:" /etc/passwd | cut -d: -f1 | tr '\n' ' '
}

function daemon_as_user {
    uid=$(id -u "$uuid")
    mcs_level=`oo-get-mcs-level $uid`
    daemon --user="$uuid" runcon -u unconfined_u -r system_r -t openshift_t -l $mcs_level "$@"
}

function openshift_origin_cron_users() {
    cron_users=()
    for u in `openshift_origin_users`; do
       if [ -z "${cron_users[*]}" ]; then
          cron_users=("$u")
       elif [ -d $GEAR_BASE_DIR/$u/$CART_DIRNAME ]; then
          cron_users=("${cron_users[@]}" "$u")
       fi
    done
    echo "${cron_users[@]}" | tr '\n' ' '
}

function run_all_scheduled_jobs() {
   freq=${1:-""}
   if [ -z "$freq" ]; then
      usage
      exit 1
   fi

   {
      log_message ":START: $freq run of all scheduled jobs"
      openshift_origin_cron_users | xargs -d' ' -I{} -n 1 -P $DOP $0 run-user {} $freq
      log_message ":END: $freq run of all scheduled jobs"
   } &> /dev/null
}


function run_user_scheduled_jobs() {
   uuid=${1:-""}
   freq=${2:-""}
   if [[ -z "$uuid" || -z "$freq" ]]; then
      usage
      exit 22
   fi
   export uuid

   # Ensure cron jobs are enabled, there's a jobs dir and there's some jobs
   # to run.
   USER_CRON_INSTANCE_DIR=${GEAR_BASE_DIR}/$uuid/$CART_DIRNAME
   [ ! -f $USER_CRON_INSTANCE_DIR/run/jobs.enabled ]  &&  return 0
   [ ! -d "$GEAR_BASE_DIR/$uuid/app-root/repo/.openshift/cron/$freq" ]  &&  return 0
   njobs=$(ls "$GEAR_BASE_DIR/$uuid/app-root/repo/.openshift/cron/$freq" | wc -l)
   [ 0 -ge ${njobs:-0} ]  &&  return 0

   # Ensure scripts are executable
   for script in "$GEAR_BASE_DIR/$uuid/app-root/repo/.openshift/cron/$freq/*"; do
       [ -x $script ] || chmod +x $script
   done

   cron_runjob="$USER_CRON_INSTANCE_DIR/bin/cron_runjobs.sh"
   cmd="$cron_runjob $freq"

   # Ensure cron's embedded in the app.
   if [ -f "$cron_runjob" ]; then
      daemon_as_user $cmd
   fi
}



# Check whether to run all or a specific user's jobs.
case "$1" in 
    run)       run_all_scheduled_jobs  "$2"       ;;
    run-user)  run_user_scheduled_jobs "$2" "$3"  ;;
    *)         usage ; exit 1                     ;;
esac

exit 0
