#!/bin/bash

CONFIG_DIR=/etc/opensips
ARCHIVE_DIR=$CONFIG_DIR/archive
CONFIG_FILE=$CONFIG_DIR/opensips.cfg
CONFIG_M4=$CONFIG_DIR/config/opensips.m4

if test -f $CONFIG_M4; then
    m4 --quiet $CONFIG_M4 > $CONFIG_FILE.tmp

    if test $? != 0; then
        echo "Error processing M4 configuration!"
        rm $CONFIG_FILE.tmp
        exit 1
    fi

    output=$(opensips -C -f $CONFIG_FILE.tmp 2>&1 >/dev/null)

    if test $? != 0; then
        echo "The generated configuration file is invalid!"
        echo -e "\n$output\n"
        rm $CONFIG_FILE.tmp
        exit 1
    fi

    if ! cmp --silent $CONFIG_FILE.tmp $CONFIG_FILE; then
        # the new config file is different from the existing one. store it and replace it.
        mkdir --parents $ARCHIVE_DIR
        ln --force $CONFIG_FILE.tmp $ARCHIVE_DIR/opensips.cfg.$(date +%Y-%m-%d_%H:%M:%S.%N)
        mv $CONFIG_FILE.tmp $CONFIG_FILE
        echo "Succesfully generated configuration file."
    else
        rm $CONFIG_FILE.tmp
        echo "Configuration file is unchanged."
    fi
else
    echo "No M4 configuration found. Nothing to do."
fi
