#!/bin/bash

# TODO: use the _XIVO_* namespace for generated variables

[ -r /etc/xivo/common.conf ] && . /etc/xivo/common.conf


echo "Generating configuration"

#### Set and check general variables ####

if [ -z "${XIVO_NET4_IP}" -o -z "${XIVO_NET4_NETMASK}" ]; then
  echo "ERROR: Network badly configured" >&2
  exit 1
fi

if [ -z "${XIVO_SMTP_ORIGIN}" ]; then
  XIVO_SMTP_ORIGIN="${XIVO_HOSTNAME}.${XIVO_DOMAIN}"
fi

XIVO_NAMESERVER_LIST=
if [ -n "${XIVO_NAMESERVERS}" ]; then
  for NS in ${XIVO_NAMESERVERS}; do
    XIVO_NAMESERVER_LIST="${XIVO_NAMESERVER_LIST}nameserver ${NS}\n"
  done
fi

if [ "${XIVO_DHCP_ACTIVE}" = "0" ]; then
   XIVO_DHCP_NETWORK_INTERFACES=""
fi

if [[ "${XIVO_DHCP_ACTIVE}" = "1" && -n "${XIVO_DHCP_POOL}" ]]; then
  _XIVO_DHCP_SUBNET="\# Include of the subnet declaration (DHCP is configured)\ninclude \"/etc/dhcp/dhcpd_subnet.conf\";"
else
  _XIVO_DHCP_SUBNET="\# Subnet declaration not specified because DHCP is not configured\n\# Use dhcpd_extra.conf for custom configuration"
fi

if [ -n "${XIVO_SMTP_MYDOMAIN}" ]; then
  _XIVO_SMTP_MYDOMAIN=${XIVO_SMTP_MYDOMAIN}
else
  _XIVO_SMTP_MYDOMAIN=${XIVO_DOMAIN}
fi

if [ -z "${XIVO_PROVD_NET4_IP}" ]; then
  XIVO_PROVD_NET4_IP="${XIVO_NET4_IP}"
fi

if [ -z "${XIVO_PROVD_HTTP_PORT}" ]; then
  XIVO_PROVD_HTTP_PORT="8667"
fi

if [ -z "${XIVO_PROVD_HTTP_BASE_URL}" ]; then
  XIVO_PROVD_HTTP_BASE_URL="http://${XIVO_PROVD_NET4_IP}:${XIVO_PROVD_HTTP_PORT}"
fi

if [ "${XIVO_PROVD_DHCP_INTEGRATION}" = "1" ]; then
  _XIVO_PROVD_DHCP_INTEGRATION='on commit {\n            execute("dxtorc",\n                    "commit",\n                    binary-to-ascii(10, 8, ".", leased-address),\n                    binary-to-ascii(16, 8, ":", suffix(hardware, 6)),\n                    pick-first-value(concat("060", binary-to-ascii(16, 8, ".", option vendor-class-identifier)), "")\n                   );\n        }'
else
  _XIVO_PROVD_DHCP_INTEGRATION=""
fi

_XIVO_MONIT_MODE=active
