#!/bin/bash -e

source $OPENSHIFT_CARTRIDGE_SDK_BASH
source $OPENSHIFT_JENKINS_DIR/bin/util

cartridge_type="jenkins"

function isrunning() {
    # Check for running app
    pid=`pgrep -f ".*java.*-jar.*jenkins.war.*--httpListenAddress=${OPENSHIFT_JENKINS_IP}.*" 2> /dev/null`
    if [ -n "$pid" ]
    then
        return 0
    fi
    # not running
    return 1
}

# Check if the server is all the way up
function is_up() {
    jenkins_url="http://${OPENSHIFT_JENKINS_IP}:8080/"

    let count=0
    while [ ${count} -lt 64 ]
    do
        url="curl -s -k -X GET --user \"${JENKINS_USERNAME}:${JENKINS_PASSWORD}\" ${jenkins_url}"
        result=`$url`
        if [ -n "$result" ]; then
            if [[ "$result" == *"Please wait while Jenkins is getting ready to work"* ]]; then
                echo "Waiting ..."
            else
                return 0
            fi
        fi
        let count=${count}+1
        sleep 2
    done
    return 1
}

function start() {
  echo "Starting $cartridge_type cartridge"

  if isrunning
  then
    echo "Application is already running!" 1>&2
    exit 0
  fi
  JENKINS_CMD="/etc/alternatives/jre/bin/java \
      -Xmx168m \
      -XX:MaxPermSize=100m \
      -Djava.awt.headless=true"

  if marker_present "disable_jenkins_udp_broadcast"; then
      JENKINS_CMD="${JENKINS_CMD} -Dhudson.udp=-1"
  fi

  if marker_present "enable_debugging"; then
      JENKINS_CMD="${JENKINS_CMD} -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=${OPENSHIFT_JENKINS_IP}:7600,suspend=n"
  fi
  
  if [ -z "$JENKINS_WAR_PATH" ]; then
    JENKINS_WAR_PATH=/usr/lib/jenkins/jenkins.war
  fi

  JENKINS_CMD="${JENKINS_CMD} ${JENKINS_OPTS} -DJENKINS_HOME=$OPENSHIFT_DATA_DIR \
      -Dhudson.slaves.NodeProvisioner.recurrencePeriod=500 \
      -Dhudson.slaves.NodeProvisioner.initialDelay=100 \
      -Dhudson.slaves.NodeProvisioner.MARGIN=100 \
      -Dhudson.model.UpdateCenter.never=true \
      -Dhudson.DNSMultiCast.disabled=true \
      -jar ${JENKINS_WAR_PATH} \
      --ajp13Port=-1 \
      --controlPort=-1 \
      --logfile=/dev/stdout \
      --httpPort=8080 \
      --handlerCountMax=45 \
      --handlerCountMaxIdle=20 \
      --httpListenAddress=$OPENSHIFT_JENKINS_IP"
  
  # Without this, international characters in job definitions
  # are not handled properly by Jenkins
  export LANG=en_US.UTF.8 
  
  nohup $JENKINS_CMD |& /usr/bin/logshifter -tag jenkins &
  
  if ! is_up; then
      echo "Timed out waiting for Jenkins to fully start"
      exit 1
  fi
}

function stop() {
  echo "Stopping $cartridge_type cartridge"

  if isrunning
  then
    kill -TERM $pid > /dev/null 2>&1
    wait_for_stop $pid
  else
    echo "Application is already stopped!" 1>&2
  fi
}

function restart() {
  stop
  start
}

function status() {
  if isrunning
  then
    client_result "Application is running"
  else
    client_result "Application is either stopped or inaccessible"
  fi
}

function reload() {
  restart
}

# Clean up any log files
function tidy() {
  client_message "Deleting jenkins logs from $OPENSHIFT_LOG_DIR"
  shopt -s dotglob
  rm -rf $OPENSHIFT_LOG_DIR/jenkins.log*
}

# Update the broker host and current system builder credentials
# in the Jenkins configuration files
function post_restore() {
  echo "Rewriting Jenkins broker and system_builder configs" 1>&2

  local openshift_server=`echo "${OPENSHIFT_BROKER_HOST}" | sed -e "s/\/*$//"`
  sed -r -i "s/<brokerHost>(.*)<\/brokerHost>/<brokerHost>$openshift_server<\/brokerHost>/g" ${OPENSHIFT_DATA_DIR}/config.xml

  local password_hash=`obfuscate_password $JENKINS_PASSWORD`
  sed -r -i "s/<passwordHash>(.*)<\/passwordHash>/<passwordHash>$password_hash<\/passwordHash>/g" ${OPENSHIFT_DATA_DIR}/users/system_builder/config.xml
}

case "$1" in
  start)         start ;;
  stop)          stop ;;
  restart)       restart ;;
  status)        status ;;
  reload)        reload ;;
  tidy)          tidy ;;
  post-restore)  post_restore ;;
  *)             exit 0
esac
