#!/bin/sh /etc/rc.common
# Copyright (C) 2014 - 2018 OpenWrt.org

START=99

NAME=kamailio
COMMAND=/usr/sbin/$NAME

RUNDIR=/var/run/$NAME
PIDFILE=$RUNDIR/$NAME.pid

LOG_ERR="/usr/bin/logger -p user.err -s -t $NAME"

USE_PROCD=1

#PROCD_DEBUG=1

check_listen() {
  local value="$1"
  local type="$2"

  local address
  local has_proto=0
  local one two three
  local tmp

  [ -z "$value" ] && {
    $LOG_ERR empty $type entry
    exit 1
  }

  # IPv6 addresses need to be enclosed in square brackets. If there are
  # square brackets in the listen entry, just copy it.
  echo "$value" | grep "\[[0-9:A-Fa-f]*\]" &> /dev/null && {
    options=$options" -l $value"
    return
  }

  # Bail if more than 2 colons.
  [ $(echo "$value" | awk -F ":" '{print NF-1}') -gt 2 ] && {
    $LOG_ERR init script does not understand $type entry \""$value"\"
    exit 1
  }

  IFS=":" read one two three << EOF
$value
EOF

  case "$one" in
    udp|tcp|tls|sctp)
      tmp="$two"
      has_proto=1
      ;;
    *)
      tmp="$one"
      ;;
  esac

  if [ "$type" = "listen" ]; then
    network_get_ipaddr address "$tmp" || address="$tmp"
  else
    network_get_ipaddr6 address "$tmp" && address="[$address]" || \
                                                     address="$tmp"
  fi

  if [ -n "$three" ]; then
    tmp="$one:$address:$three"
  elif [ -n "$two" ]; then
    if [ $has_proto = 1 ]; then
      tmp="$one:$address"
    else
      tmp="$address:$two"
    fi
  else
    tmp="$address"
  fi

  options=$options" -l $tmp"
}

start_service() {
  local enabled
  local user
  local group
  local shm_memory
  local pkg_memory
  local cfg_file
  local options

  config_load $NAME

  config_get_bool enabled general enabled 0

  if [ $enabled -eq 0 ]; then
    $LOG_ERR service not enabled in /etc/config/$NAME
    exit 1
  fi

  config_get user       general user       $NAME
  config_get group      general group      $NAME
  config_get shm_memory general shm_memory 8
  config_get pkg_memory general pkg_memory 2
  config_get cfg_file   general cfg_file   /etc/$NAME/$NAME.cfg
  config_get options    general options

  . /lib/functions/network.sh

  config_list_foreach general listen  check_listen listen
  config_list_foreach general listen6 check_listen listen6

  if [ ! -d $RUNDIR ]; then
    mkdir -p $RUNDIR
    chown "$user":"$group" $RUNDIR
  fi

  procd_open_instance
  procd_set_param command $COMMAND
  procd_append_param command \
    -P $PIDFILE \
    -f "$cfg_file" \
    -m "$shm_memory" \
    -M "$pkg_memory" \
    $options \
    -u "$user" \
    -g "$group" \
    -DD -E
  # forward stderr to logd
  procd_set_param stderr 1
  procd_close_instance
}

