#!/bin/sh
# -*- sh-basic-offset: 2 -*-

##
# Copyright (c) 2005-2017 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

##
# WARNING: This script is intended for use by developers working on
# the Calendar Server code base.  It is not intended for use in a
# deployment configuration.
#
# DO NOT use this script as a system startup tool (eg. in /etc/init.d,
# /Library/StartupItems, launchd plists, etc.)
#
# For those uses, install the server properly (eg. with "./run -i
# /tmp/foo && cd /tmp/foo && pax -pe -rvw . /") and use the caldavd
# executable to start the server.
##

set -e;
set -u;

wd="$(cd "$(dirname "$0")/.." && pwd)";

do_setup="false";

#
# Usage
#

      config="${wd}/conf/caldavd-dev.plist";
     reactor="";
 plugin_name="caldav";
service_type="Combined";
         run="true";
   daemonize="-X -L";
        kill="false";
     restart="false";
     profile="";


usage () {
  program="$(basename "$0")";

  if [ "${1--}" != "-" ]; then
    echo "$@";
    echo;
  fi;

  echo "Usage: ${program} [-hvgsfnpdlkrR] [-K key] [-iIb dst] [-t type] [-S statsdirectory] [-P plugin]";
  echo "Options:";
  echo "  -h  Print this help and exit";
  echo "  -d  Run caldavd as a daemon";
  echo "  -k  Stop caldavd";
  echo "  -r  Restart caldavd";
  echo "  -t  Select the server process type (Master, Slave or Combined) [${service_type}]";
  echo "  -S  Write a pstats object for each process to the given directory when the server is stopped.";
  echo "  -P  Select the twistd plugin name [${plugin_name}]";
  echo "  -R  Twisted Reactor plugin to execute [${reactor}]";

  if [ "${1-}" = "-" ]; then
    return 0;
  fi;
  exit 64;
}


# Parse command-line options to set up state which controls the behavior of the
# functions in build.sh.
parse_options () {
  OPTIND=1;
  print_path="false";
  while getopts "ahnpdlkrc:i:I:b:t:S:P:R:" option; do
    case "${option}" in
      '?') usage; ;;
      'h') usage -; exit 0; ;;
      'k')         kill="true"; ;;
      'r')      restart="true"; ;;
      'd')    daemonize=""; ;;
      'l')    daemonize="-X"; ;;
      'P')  plugin_name="${OPTARG}"; ;;
      'c')       config="${OPTARG}"; ;;
      'R')      reactor="-R ${OPTARG}"; ;;
      't') service_type="${OPTARG}"; ;;
      'S')      profile="-p ${OPTARG}"; ;;
    esac;
  done;
  shift $((${OPTIND} - 1));
  if [ $# != 0 ]; then
    usage "Unrecognized arguments:" "$@";
  fi;
}


# Actually run the server.  (Or, exit, if things aren't sufficiently set up in
# order to do that.)
run () {


  echo "Using ${python} as Python";

  if "${run}"; then
    cd "${wd}";
    if [ ! -d "${wd}/data" ]; then
      mkdir "${wd}/data";
    fi;

    echo "";
    echo "Starting server...";
    echo ""${wd}/bin/caldavd" ${daemonize} -f "${config}" -P "${plugin_name}" -t "${service_type}" ${reactor} ${profile}";

    exec "${wd}/bin/caldavd" ${daemonize}  \
        -f "${config}"                    \
        -P "${plugin_name}"               \
        -t "${service_type}"              \
        ${reactor}                        \
        ${profile};
    cd /;
  fi;
}

kill_pids_by_name() {
  echo "Killing processs by name user and name..";
  "/usr/bin/pkill" "-u" "cpanel-ccs" "-f" "CalendarServer" &
  echo "Done killing processes"
}

# The main-point of the 'run' script: parse all options, decide what to do,
# then do it.
run_main () {

  python="/opt/cpanel-ccs/.develop/virtualenv/bin/python";
  export PYTHON="${python}";


  parse_options "$@";

  if "${print_path}"; then
    exec "${wd}/bin/environment" PYTHONPATH;
  fi;

  # About to do something for real; let's enumerate (and depending on options,
  # possibly download and/or install) the dependencies.

  if "${kill}" || "${restart}"; then
    echo "kill = ${kill}"
    echo "restart = ${restart}"
    skip_final_kill=0;
    killed=0;
    pidfile="$("${wd}/bin/calendarserver_config" "-f" "${config}" "PIDFile")";
    # Split key and value on "=" and just grab the value
    IFS="="; set ${pidfile}; pidfile="$2"; unset IFS;
    # Set full path for pidfile based on relative path
    pidfile="/opt/cpanel-ccs/$pidfile";
    echo "pidfile = $pidfile";
    if [ ! -r "${pidfile}" ]; then
      echo "Unreadable PID file: ${pidfile}";
      skip_final_kill=1;
      kill_pids_by_name;
      killed=1;
      if [ "${kill}" == "true" ]; then
          exit 1;
      fi;
    fi;
    pid="$(cat "${pidfile}" | head -1)";
    if [ -z "${pid}" ]; then
      echo "No PID in PID file: ${pidfile}";
      kill_pids_by_name;
      skip_final_kill=1;
      killed=1;
      exit 1;
    fi;

    if [ ! -z "${skip_final_kill}" ]; then
      echo "Killing process ${pid}";
      kill -TERM "${pid}";
    fi;

    if ! "${restart}"; then
      exit 0;
    else
      daemonize=""
    fi;
  fi;

  run;
}


run_main "$@";

