#!/sbin/openrc-run

command="/usr/bin/exabgp"
command_args="/etc/exabgp/exabgp.conf"
command_background="true"
pidfile="/var/run/${RC_SVCNAME}.pid"

extra_started_commands="reload"
extra_stopped_commands="setup"

description="exabgp daemon"
description_reload="Reload exabgp using USR1"


depend() {
    use net
}

start_pre() {
  required_files="/etc/exabgp/exabgp.env /etc/exabgp/exabgp.conf"
  for file in $required_files; do
    case "$file" in
      *.env)
      if [ ! -f "$file" ]; then
        eerror "env file ${file} missing run '/etc/init.d/exabgp setup' to create the file"
        exit 1
      fi
      ;;
    *.conf)
      if [ ! -f "$file" ]; then
        eerror "conf file ${file} does not exist, create manually"
        exit 1
      fi
      ;;
    *)
      ;;
    esac
  done
  mkdir /run/exabgp 2>/dev/null
  if [ ! -p /run/exabgp/exabgp.in ]; then
    mkfifo /run/exabgp/exabgp.in 2>/dev/null
  fi
  if [ ! -p /run/exabgp/exabgp.out ]; then
    mkfifo /run/exabgp/exabgp.out 2>/dev/null
  fi
}

reload() {
    ebegin "Reloading $name"
    start-stop-daemon --signal USR1 --pidfile "$pidfile"
    eend ${?}
}

setup() {
    ebegin "Creating /etc/exabgp/exabgp.env with defaults"
    if [ ! -f "/etc/exabgp/exabgp.env" ]; then
    "$command" --fi | sed "s/nobody/$exabgp_user/g" > /etc/exabgp/exabgp.env
      eend ${?}
    fi
    eend ${?}
}
