#!/usr/bin/env bash
#
### BEGIN INIT INFO
# Provides: cuttlefish-host_orchestrator
# Required-Start: $network $remote_fs nginx
# Required-Stop: $network $remote_fs
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Cuttlefish Host Orchestrator service
# Description: The Host Orchestrator service provides the signaling
#              server used by all cuttlefish instances running in this
#              host as well as orchestration capabilities.
### END INIT INFO
#
# Copyright (C) 2021 The Android Open Source Project
#
# 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.

# Make sure calls to this script get redirected to systemctl when
# using systemd

. /lib/lsb/init-functions

if [ -f /etc/default/cuttlefish-host_orchestrator ]; then
    . /etc/default/cuttlefish-host_orchestrator
fi

orchestrator_cvd_artifacts_dir=${orchestrator_cvd_artifacts_dir:-"/var/lib/cuttlefish-common"}

USER="httpcvd"
RUN_DIR="/run/cuttlefish"
ORCHESTRATOR_BIN="/usr/lib/cuttlefish-common/bin/host_orchestrator"
ORCHESTRATOR_PIDFILE="${RUN_DIR}"/host_orchestrator.pid
ORCHESTRATOR_LOGFILE="${RUN_DIR}"/host_orchestrator.log
ASSET_DIR="/usr/share/cuttlefish-common/operator"

set_config_expr() {
  echo "\${$2+"export $1=\$$2"}"
}

setup_nginx() {
  DIR="/etc/cuttlefish-orchestration/ssl/cert"
  CERT_FILE="${DIR}/cert.pem"
  KEY_FILE="${DIR}/key.pem"
  mkdir -p "${DIR}"
  openssl req \
    -newkey rsa:4096 \
    -x509 \
    -sha256 \
    -days 36000 \
    -nodes \
    -out "${CERT_FILE}" \
    -keyout "${KEY_FILE}" \
    -subj "/C=US"
  ln -s /etc/nginx/sites-available/cuttlefish-orchestration.conf \
    /etc/nginx/sites-enabled/cuttlefish-orchestration.conf
  service nginx reload
}

prepare_run_dir() {
  mkdir -p "${RUN_DIR}"
  chown "${USER}" "${RUN_DIR}"
}

start_orchestrator() {
  mkdir -p  "${orchestrator_cvd_artifacts_dir}"
  chown "${USER}:" "${orchestrator_cvd_artifacts_dir}"

  args=("--log_file=${ORCHESTRATOR_LOGFILE}")
  if [[ -n "${orchestrator_http_port}" ]]; then
    args+=("--http_port=${orchestrator_http_port}")
  fi
  if [[ -n "${orchestrator_android_build_url}" ]]; then
    args+=("--android_build_url=${orchestrator_android_build_url}")
  fi
  if [[ -n "${orchestrator_cvd_artifacts_dir}" ]]; then
    args+=("--cvd_artifacts_dir=${orchestrator_cvd_artifacts_dir}")
  fi
  if [[ -n "${operator_http_port}" ]]; then
    args+=("--operator_http_port=${operator_http_port}")
  fi
  if [[ -n "${orchestrator_listen_address}" ]]; then
    args+=("--listen_addr=${orchestrator_listen_address}")
  fi
  if [[ -n "${build_api_credentials_use_gce_metadata}" ]]; then
    args+=("--build_api_credentials_use_gce_metadata=${build_api_credentials_use_gce_metadata}")
  fi

  start-stop-daemon --start \
    --pidfile "${ORCHESTRATOR_PIDFILE}" \
    --chuid "${USER}" \
    --chdir "${ASSET_DIR}" \
    --background --no-close \
    --make-pidfile \
    --exec "${ORCHESTRATOR_BIN}" -- "${args[@]}"
}

start() {
  # Note: Use `Wants=` option when migrating to systemd unit files rather
  # than starting the systemd-journal-gatewayd service manually.
  # https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html
  service systemd-journal-gatewayd start

  setup_nginx

  prepare_run_dir

  start_orchestrator
}

stop() {
  start-stop-daemon --stop \
    --pidfile "${ORCHESTRATOR_PIDFILE}" \
    --remove-pidfile \
    --exec "${ORCHESTRATOR_BIN}"
}

status() {
  # Return
  #   0 if daemon is running
  #   1 if daemon is dead and pid file exists
  #   3 if daemon is not running
  #   4 if daemon status is unknown
  start-stop-daemon --start --quiet --pidfile "${ORCHESTRATOR_PIDFILE}" --exec ${ORCHESTRATOR_BIN} --test > /dev/null
  case "${?}" in
    0) [ -e "${ORCHESTRATOR_PIDFILE}" ] && return 1 ; return 3 ;;
    1) return 0 ;;
    *) return 4 ;;
  esac
}

usage() {
    echo $0: start\|stop\|status
}

if test $# != 1; then
    usage
else
    case "$1" in
        --help)
            usage 0
            ;;
        start|stop|status)
            "$1"
            ;;
        restart|force-reload|condrestart|try-restart)
            stop && start
            ;;
        reload)
            # Nothing to do
            ;;
        shutdown)
            stop
            ;;
        *)
            usage
            ;;
    esac
fi
exit 0
