#!/bin/sh -e

# Simple boot script for Erlang/OTP releases that can be used in systemd unit files.
#
# Copyright 2025 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
# Author: Vadim Yanitskiy <vyanitskiy@sysmocom.de>
#
# SPDX-License-Identifier: MPL-2.0
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0.  If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

APP_NAME=osmo-s1gw

ROOTDIR=${ROOTDIR:-"/usr/lib/${APP_NAME}"}
CONFIG="/etc/osmocom/${APP_NAME}.config"
COOKIE="${APP_NAME}"
NODE_NAME="${APP_NAME}@$(uname -n)"
ERL_SHELL="-noshell -noinput"

print_usage() {
  echo "Usage: $0 [-s] [-r ROOTDIR] [-c CONFIG] [-C COOKIE] [-n NAME@HOST]"
}

print_help() {
  echo "  -h    This message"
  echo "  -s    Enable interactive shell"
  echo "  -r    Application's root directory (default: ${ROOTDIR})"
  echo "  -c    Config file path (default: ${CONFIG})"
  echo "  -C    Erlang node cookie (default: ${COOKIE})"
  echo "  -n    Erlang node name (default: ${NODE_NAME})"
}

# Parse command line options, if any
while getopts "c:C:hn:r:s" opt; do
  case "$opt" in
    c)
      CONFIG="$OPTARG"
      ;;
    C)
      COOKIE="$OPTARG"
      ;;
    n)
      NODE_NAME="$OPTARG"
      ;;
    r)
      ROOTDIR=$(realpath "$OPTARG")
      ;;
    s)
      ERL_SHELL="-shell"
      ;;
    h)
      print_usage
      print_help
      exit 1
      ;;
    *)
      print_usage
      exit 1
      ;;
  esac
done

# Make sure that the application's root directory exists
if [ ! -d "${ROOTDIR}" ]; then
  echo "Error: ROOTDIR=${ROOTDIR} does not exist"
  echo "Please specify the root directory using '-r' or via the environment"
  exit 1
fi

# Determine the ERTS directory path (if not set)
if [ -z "${ERTS_DIR}" ]; then
  # Parse the ERTS version from rebar3-generated bootstrap script
  ERTS_VSN=$(grep "^ERTS_VSN=" ${ROOTDIR}/bin/${APP_NAME} | cut -d'"' -f2)
  ERTS_DIR=${ERTS_DIR:-"${ROOTDIR}/erts-${ERTS_VSN}"}
fi

# Determine the release directory path (if not set)
if [ -z "${REL_DIR}" ]; then
  # Parse the release version from rebar3-generated bootstrap script
  REL_VSN=$(grep "^REL_VSN=" ${ROOTDIR}/bin/${APP_NAME} | cut -d'"' -f2)
  REL_DIR="${ROOTDIR}/releases/${REL_VSN}"
fi

# Determine the boot script name
[ -f "${REL_DIR}/${APP_NAME}.boot" ] && BOOTFILE="${APP_NAME}" || BOOTFILE=start

# erlexec requires BINDIR to be set
export BINDIR="${ERTS_DIR}/bin"

exec ${BINDIR}/erlexec \
  +C multi_time_warp \
  -boot "${REL_DIR}/${BOOTFILE}" \
  -config "${CONFIG}" \
  -setcookie "${COOKIE}" \
  -sname "${NODE_NAME}" \
  -mode embedded \
  ${ERL_SHELL}

# vim:set ts=2 sw=2 et:
