#!/bin/sh

FS=freeswitch
LOGGER="/usr/bin/logger -t ${FS}-hotplug"
LOG_ERR="$LOGGER -p user.err --"
LOG_NOTICE="$LOGGER -p user.notice --"
LOG_WARN="$LOGGER -p user.warn --"

[ "$ACTION" = ifup ] || exit 0

. /lib/functions.sh
config_load $FS

config_get FS_HOTPLUG_INTERFACE hotplug interface

[ -n "$FS_HOTPLUG_INTERFACE" ] || exit 0

[ "$INTERFACE" = "$FS_HOTPLUG_INTERFACE" ] || exit 0

pgrep $FS &> /dev/null
if [ $? -eq 0 ]; then
  $LOG_NOTICE stopping $FS
  /etc/init.d/$FS stop &> /dev/null
  pgrep $FS &> /dev/null
  if [ $? -eq 0 ]; then
    $LOG_ERR failed to stop $FS
    exit 1
  else
    $LOG_NOTICE $FS stopped
  fi
fi

config_get FS_HOTPLUG_TIMEOUT hotplug timeout

[ "$FS_HOTPLUG_TIMEOUT" -gt 0 ] 2> /dev/null || unset FS_HOTPLUG_TIMEOUT
TIMEOUT="${FS_HOTPLUG_TIMEOUT:-60}"

config_get FS_HOTPLUG_MOUNTPOINT hotplug mount_point

# Mount condition, idea lifted from OpenWrt wiki
[ -n "$FS_HOTPLUG_MOUNTPOINT" ] && {

  if ! [ -d "$FS_HOTPLUG_MOUNTPOINT" ]; then
    $LOG_ERR "$FS_HOTPLUG_MOUNTPOINT" not a valid mount point
    exit 1
  fi

  mnt="$FS_HOTPLUG_MOUNTPOINT"
  notReady=start
  timeout=$TIMEOUT

  while [ -n "$notReady" -a $timeout -gt 0 ]; do
    if [ "$notReady" != start ]; then
      $LOG_NOTICE "$mnt" not yet mounted, timeout in $timeout s
      sleep 5
      timeout=$(($timeout-5))
    fi

    notReady=

    result=$(cat /proc/mounts | awk '{print $2}' | grep "^$mnt\$")
    if [ -z "$result" ]; then
      notReady="$mnt not ready yet"
    fi
  done

  if [ -n "$notReady" ]; then
    $LOG_ERR "$mnt" still not mounted
    $LOG_ERR not starting $FS
    exit 1
  else
    $LOG_NOTICE "$mnt" mounted
  fi

}

config_get_bool FS_HOTPLUG_NTPD hotplug ntpd 0

# ntpd condition
[ $FS_HOTPLUG_NTPD -eq 1 ] && {

  type ntpq &> /dev/null
  [ $? -eq 0 ] || {
    $LOG_ERR ntpq utility not found
    exit 1
  }

  pgrep ntpd &> /dev/null || {
    $LOG_ERR ntpd not running
    exit 1
  }

  notReady=start
  timeout=$TIMEOUT

  while [ -n "$notReady" -a $timeout -gt 0 ]; do
    if [ "$notReady" != start ]; then
      $LOG_NOTICE system time not in sync yet, timeout in $timeout s
      sleep 5
      timeout=$(($timeout-5))
    fi

    notReady=

    result=$(ntpq -c 'timeout 300' -c 'rv 0 stratum' 2> /dev/null | \
                    awk -F '=' '{print $2}' | grep -o -E '^[0-9]+')
    if [ -z $result ]; then
      $LOG_WARN failed to extract stratum from ntpd
      notReady="unable to extract stratum"
    else
      $LOG_NOTICE ntpd stratum $result
      if [ $result -lt 16 ] 2> /dev/null; then
        result=$(ntpq -c 'timeout 300' -c 'rv 0 offset' 2> /dev/null \
                 | awk -F '=' '{print $2}' | grep -o -E '^-?[0-9]+')
        if [ -z $result ]; then
          $LOG_WARN failed to extract offset from ntpd
          notReady="unable to extract offset"
        else
          # "-0" looks stupid, so remove "-"
          result=$(echo $result | grep -o '[0-9]*')
          $LOG_NOTICE ntpd to system time offset \+\/\- $result ms
          # If offset < 100 ms consider system time in sync
          [ $result -lt 100 ] || notReady="system time not in sync yet"
        fi
      else
        notReady="ntpd not in sync yet"
      fi
    fi
  done

  if [ -n "$notReady" ]; then
    $LOG_ERR system time still not in sync
    $LOG_ERR not starting $FS
    exit 1
  else
    $LOG_NOTICE system time in sync
  fi

}

/etc/init.d/$FS start &> /dev/null
# Wait a bit in order for pgrep to be able to find the new process
sleep 1
pgrep $FS &>/dev/null
if [ $? -eq 0 ]; then
  $LOG_NOTICE started $FS due to \"ifup "$INTERFACE"\" event
else
  $LOG_ERR start of $FS due to \"ifup "$INTERFACE"\" event failed
  exit 1
fi
