#!/bin/sh

FINDBIN=$(cd -- "$(dirname "$0")" && pwd)
. "$FINDBIN/common.sh"


if [ $# -ne 0 ]; then
    ./dev_scripts/stop_munin-node

    rm -rf sandbox
    mkdir sandbox
    make clean || exit
    echo "**********************************************************************"
fi

make "DESTDIR=$DESTDIR" "HTMLDIR=$DESTDIR/www/munin" || exit
# Override users and groups with the current user - otherwise "install" fails, if these users
# and groups are missing in the local system.
fakeroot make \
        install-common-prime \
        install-master-prime \
        install-node-prime \
        install-plugins-prime \
        install-man install-async \
        "DESTDIR=$DESTDIR" \
        "HTMLDIR=$DESTDIR/www/munin" \
        "USER=$(id -u)" \
        "CGIUSER=$(id -u)" \
        "PLUGINUSER=$(id -u)" \
        "GROUP=$(id -g)" \
    || exit


if [ $# -ne 0 ]; then
    echo "**********************************************************************"
    fakeroot make install-plugins-prime install-plugins-java "DESTDIR=$DESTDIR" "HTMLDIR=$DESTDIR/www/munin" || exit
    echo "**********************************************************************"
    perl -pi -e "s/port 4949/port 4948/; 
                 s/user root/user $(id -n -u)/;
                 s/group root/group $(id -n -g)/;
                 s|^(port .*)|\$1

tls disabled
tls_private_key $BASEDIR/common/t/tls/node_key.pem
tls_certificate $BASEDIR/common/t/tls/node_cert.pem
tls_ca_certificate $BASEDIR/common/t/tls/CA/ca_cert.pem
tls_verify_certificate yes
tls_verify_depth 5
|; " "$DESTDIR/etc/opt/munin/munin-node.conf"

    perl -pi -e "s/(address 127\\.0\\.0\\.1)/\$1\\n    port 4948/;
                 s|(# a simple host tree)|tls disabled
tls_private_key $BASEDIR/common/t/tls/master_key.pem
tls_certificate $BASEDIR/common/t/tls/master_cert.pem
tls_ca_certificate $BASEDIR/common/t/tls/CA/ca_cert.pem
tls_verify_certificate yes
tls_verify_depth 5

\$1|" "$DESTDIR/etc/opt/munin/munin.conf"

    echo "**********************************************************************"
    ./dev_scripts/run munin-node-configure --shell --families=contrib,auto | sh -x
fi
