#!/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.
##

set -e;
set -u;

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

. "${wd}/bin/_build.sh";

init_build > /dev/null;

sim="${wd}/contrib/performance/loadtest/sim.py";

##
# Command line handling
##

   verbose="";
    config="${wd}/contrib/performance/loadtest/standard-configs/accelerated-activity-config.plist";
   clients="${wd}/contrib/performance/loadtest/standard-configs/accelerated-activity-clients.plist";
   runtime="--runtime 300";
   logfile="";

usage ()
{
  program="$(basename "$0")";
  echo "Usage: ${program} [-r RUNTIME] [-l LOGFILE]";
  echo "Options:";
  echo "        -r  Set the runtime";
  echo "        -l  Log file";

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

while getopts 'hl:r:' option; do
  case "$option" in
    '?') usage; ;;
    'h') usage -; exit 0; ;;
    'r') runtime="--runtime=${OPTARG}"; ;;
    'l') logfile="--logfile=${OPTARG}"; ;;
  esac;
done;

shift $((${OPTIND} - 1));

##
# Do The Right Thing
##

do_setup="false";
develop > /dev/null;

# Set up sandbox

sandboxdir="/tmp/sim_server_sandbox💣"
sandboxdir_u="/tmp/sim_server_sandbox\ud83d\udca3"

if [ -d "${sandboxdir}" ]; then
  rm -rf "${sandboxdir}"
fi;

configdir="${sandboxdir}/Config"
datadir="${sandboxdir}/Data"

configdir_u="${sandboxdir_u}/Config"
datadir_u="${sandboxdir_u}/Data"

mkdir -p "${sandboxdir}/Config" "${sandboxdir}/Logs" "${sandboxdir}/Run" "${datadir}/Documents"

cp conf/caldavd-test.plist "${configdir}/caldavd-sim.plist"
cp conf/auth/proxies-test.xml "${datadir}/proxies-sim.xml"
cp conf/auth/resources-test.xml "${datadir}/resources-sim.xml"
cp conf/auth/augments-test.xml "${datadir}/augments-sim.xml"
cp conf/auth/accounts-test.xml "${datadir}/accounts-sim.xml"

# Modify the plist

python -c "import plistlib; f=plistlib.readPlist('${configdir}/caldavd-sim.plist'); f['HTTPPort'] = 18008; f['BindHTTPPorts'] = [18008]; f['SSLPort'] = 18443; f['BindSSLPorts'] = [18443]; f['Notifications']['Services']['AMP']['Port'] = 62312; f['ServerRoot'] = u'${sandboxdir_u}'; f['ConfigRoot'] = 'Config'; f['RunRoot'] = 'Run'; f['ProxyLoadFromFile'] = u'${datadir_u}/proxies-sim.xml'; f['ResourceService']['params']['xmlFile'] = u'${datadir_u}/resources-sim.xml'; f['DirectoryService']['params']['xmlFile'] = u'${datadir_u}/accounts-sim.xml'; f['AugmentService']['params']['xmlFiles'] = [u'${datadir_u}/augments-sim.xml']; f['Authentication']['Kerberos']['Enabled'] = False; plistlib.writePlist(f, '${configdir}/caldavd-sim.plist');"

# Modify config to update ports and other bits

cp "${config}" "${configdir}/sim-config.plist"
config="${configdir}/sim-config.plist"
python -c "import plistlib; f=plistlib.readPlist('${configdir}/sim-config.plist'); f['servers']['PodA']['uri'] = f['servers']['PodA']['uri'].rsplit(':', 1)[0] + ':18443'; f['clientDataSerialization']['UseOldData'] = False; f['servers']['PodA']['ampPushPort'] = 62312; plistlib.writePlist(f, '${configdir}/sim-config.plist');"

# Modify clients to update ports and other bits

cp "${clients}" "${configdir}/sim-clients.plist"
clients="${configdir}/sim-clients.plist"

# Start the server

"${wd}/bin/run" -nd -c "${configdir}/caldavd-sim.plist"

/bin/echo -n "Waiting for server to start up..."

while [ ! -f "${sandboxdir}/Run/caldav-instance-0.pid" ]; do
  sleep 1
  /bin/echo -n "."
done;

echo "Server has started"

# Don't exit if sim.py fails, because we need to clean up afterwards.

set +e

# Run Sim

echo "Starting Sim run"

"${python}" "${sim}" --config "${config}" --clients "${clients}" "${runtime}" "${logfile}"

# Capture exit status of sim.py to use as this script's exit status.

STATUS=$?

# Re-enable exit on failure incase run -nk fails

set -e

echo "Stopping server"
"${wd}/bin/run" -nk -c "${configdir}/caldavd-sim.plist"

# Exit with the exit status of sim.py, to reflect the sim's result

exit $STATUS
