#!/bin/bash


MONIT_CHECKS=/usr/share/xivo-monitoring/checks
MONIT_CONF_DIR=/etc/monit/conf.d

activate_check()
{
    local check=$1
    
    # cleanup broken link
    find $MONIT_CONF_DIR -type l -xtype l -exec rm {} \;
    
    if [ -e $MONIT_CONF_DIR/$check ] && [ ! -L $MONIT_CONF_DIR/$check ]; then
      rm $MONIT_CONF_DIR/$check
    fi
    
    if [ ! -e $MONIT_CONF_DIR/$check ]; then
      ln -s $MONIT_CHECKS/$check $MONIT_CONF_DIR/$check
    fi
}

# known services
for check in $MONIT_CHECKS/*; do
    service=$(basename $check)
    activate_check $service
done

# Server config
# (backup old file)
monit_file="/etc/monit/monitrc"
if [ -e $monit_file ]; then
    today=$(date +%Y%m%d%H%M%S)
    cp $monit_file $monit_file.$today
fi
cp $monit_file.tmpl $monit_file

# restart service to take changes into account
invoke-rc.d monit restart >/dev/null
