#!/bin/sh
#
# License: Copyright 2015 SpinetiX. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#
# Copyright 1999-2003 MontaVista Software, Inc.
# Copyright 2002, 2003, 2004 Sony Corporation
# Copyright 2002, 2003, 2004 Matsushita Electric Industrial Co., Ltd.
#
### BEGIN INIT INFO
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 5
# Default-Stop:
# Short-Description: Starting/stopping mDNS for SPX discovery
# Description: Starting/stopping mDNS for SPX discovery
### END INIT INFO

# Init script information
NAME=spxmanage-mdns
DESC="SPX Bonjour services"

# config / daemon
DAEMON=/usr/sbin/avahi-daemon
BASENAME=avahi-daemon
SAFEINDICATOR=/var/run/raperca/safe-mode
VOLATILESERVICESDIR=/var/run/spxmanage/avahi-services
SERVICESDIR=/etc/avahi/services
TEMPLATESDIR=/usr/share/spxmanage/avahi-services
CONFWEB="$SERVICESDIR"/spxmanage.service
CONFWEBDAV="$SERVICESDIR"/spxmanage-webdav.service
CONFWEBDAVS="$SERVICESDIR"/spxmanage-webdavs.service
CONFPLAYER="$SERVICESDIR"/raperca.service
CONFIM="$SERVICESDIR"/raperca-im.service
RCMAIN=/usr/share/resources/default/init/main
RCRAPERCA=/usr/share/resources/default/init/raperca
SPXHTDEFS=/etc/apache2/conf.d/01-spxmanage-defs.conf

# Load init script configuration
[ -f /etc/default/$NAME ] && . /etc/default/$NAME

# Load apache2 configuration to detect SSL
[ -f /etc/default/apache2 ] && . /etc/default/apache2

# Load output from licensecheck
[ -f /run/licensecheck/discovery.conf ] && . /run/licensecheck/discovery.conf

# Load resources
[ -f "$RCMAIN" ] && . "$RCMAIN"
[ -f "$RCRAPERCA" ] && . "$RCRAPERCA"

# Load identifiers
[ -f /etc/spinetix/identifiers ] && . /etc/spinetix/identifiers

# Source the init script functions
. /etc/init.d/functions
. /etc/spxmanage/init-functions

# Verify daemons are installed
if [ ! -x $DAEMON -a "$1" != "stop" ]; then
    echo -n "Not starting $DESC $NAME, $DAEMON not installed"
    warning
    echo
    exit 0
fi

is_mounted() {
    local dev mnt type opts dump pass junk
    local path="${1%/}"
    local ret=1

    while read dev mnt type opts dump pass junk; do
        [ "$mnt" = "$path" ] || continue
        ret=0
        break
    done < /proc/mounts

    return $ret 
}

gen_service() {
    local sedprog="$1"
    local dest="$2"

    sed -e "$sedprog" "${TEMPLATESDIR}/${dest##*/}".tmpl > "$dest"
}

update_services() {
    local mode sn fw netapion netapiport name model mport srpv
    local service_sn user_sn board_sn system_sn chassis_sn
    local no_cport type_im

    if [ -f $SAFEINDICATOR ]; then
        mode="safe"
    else
        mode="normal"
    fi
    if [ -e /etc/spxmanage/configured ]; then
        configured="yes"
    else
        configured="no"
    fi
    if grep -q '^[[:space:]]*Define[[:space:]]\+SSL_DISABLE_SRP\($\|[[:space:]]\)' "$SPXHTDEFS"; then
      srpv=no # SRP is disabled
    else
      srpv=yes # SRP is enabled
    fi 
    if [ -n "$DISCOVERY_NO_IM" ]; then
        type_im=
    else
        type_im="$rc_dns_sd_type_im"
    fi
    service_sn="${SPX_SN:-unknown}"
    user_sn="${SPX_USER_SN}"
    board_sn="${SPX_BOARD_SN}"
    system_sn="${SPX_SYSTEM_SN}"
    chassis_sn="${SPX_CHASSIS_SN}"
    [ -n "$user_sn" ] && sn="$user_sn" || sn="$service_sn"
    fw="$(sed -n -e '/VERSION_ID=/{s/^[^=]*=//;s/^['\''\"]//;s/['\''\"][[:space:]]*$//;p;}' /etc/os-release)"
    netapion="$(sed -ne "/\bremoteClientsEnabled=/{s/.*\bremoteClientsEnabled=['\"]\([^'\"]*\).*/\1/;p}" /etc/raperca/spxconfig.xml)"
    netapiport="$(sed -ne "/\bsharedVarPort=/{s/.*\bsharedVarPort=['\"]\([^'\"]*\).*/\1/;p}" /etc/raperca/spxconfig.xml)"
    name="$(sed -ne "/\bdeviceName=/{s/.*\bdeviceName=['\"]\([^'\"]*\).*/\1/;p}" /etc/raperca/spxconfig.xml)"
    [ -n "$name" ] || name="$sn"
    [ -n "$netapiport" ] || netapion="false"
    model="$rc_model"
    type_player="$rc_dns_sd_type_player"
    
    load_web_server_opts "$ENABLESSL" "$rc_host_prefix" "$service_sn"

    # Prefer to declare plain HTTP port for management so as to ensure maximum compatibility.
    if [ "$NOHTTP" != "yes" ]; then
        mport=80
    elif [ "$NOHTTPS" != "yes" ]; then
        mport=443
    else
        mport=0
    fi

    if [ -n "$DISCOVERY_NO_PUBLISH" -o "$NOHTTPPUBLISH" = "yes" ]; then
        no_cport=true
    else
        no_cport="$rc_dns_sd_player_no_cport"
    fi

    ss="s!@@name@@!$name!g;s!@@mode@@!$mode!g;s!@@configured@@!$configured!g;s!@@model@@!$model!g;s!@@type_player@@!$type_player!g;s!@@type_im@@!$type_im!g;s!@@sn@@!$sn!g;s!@@fw@@!$fw!g;s!@@mport@@!$mport!g;s!@@im-port@@!$netapiport!g"
    [ "$service_sn" != "$sn" ] && ss="s!@@service_sn@@!$service_sn!g;$ss" || ss="/@@service_sn@@/d;$ss"
    [ -n "$board_sn" -a -z "$user_sn" ] && ss="s!@@board_sn@@!$board_sn!g;$ss" || ss="/@@board_sn@@/d;$ss"
    [ -n "$system_sn" -a -z "$user_sn" ] && ss="s!@@system_sn@@!$system_sn!g;$ss" || ss="/@@system_sn@@/d;$ss"
    [ -n "$chassis_sn" -a -z "$user_sn" ] && ss="s!@@board_sn@@!$chassis_sn!g;$ss" || ss="/@@chassis_sn@@/d;$ss"
    if [ -n "$no_cport" ]; then
        ss="/\bcport=/d;/\bscport=/d;$ss"
    else
        [ "$NODAVHTTP" = "yes" -o "$HTTPREDIRECT" = "yes" ] && ss="/\bcport=/d;$ss"
        [ "$NOHTTPS" = "yes" ] && ss="/\bscport=/d;$ss"
    fi
    if [ -n "$HTTPSHOST" ]; then
        ss="s!@@fqdn@@!$HTTPSHOST!g;$ss"
    else
        ss="/\bfqdn=/d;$ss"
    fi
    if [ "$srpv" != "yes" ]; then
        ss="/>srpv</d;$ss"
    fi
    local ret=0

    # as the files will most of the time be identical to what is
    # already there skip overwritingif identical to avoid unneeded
    # writes to root filesystem

    if [ "$NOHTTP" != "yes" -o "$NOHTTPS" != "yes" ]; then
        gen_service "$ss" "$CONFWEB" || ret=1
    else
        rm -f "$CONFWEB" || ret=1
    fi
    if [ -z "$no_cport" ]; then
        if [ "$NODAVHTTP" != "yes" -a "$HTTPREDIRECT" != "yes" ]; then
            gen_service "$ss" "$CONFWEBDAV" || ret=1
        else
            rm -f "$CONFWEBDAV" || ret=1
        fi
        if [ "$NOHTTPS" != "yes" ]; then
            gen_service "$ss" "$CONFWEBDAVS" || ret=1
        else
            rm -f "$CONFWEBDAVS" || ret=1
        fi
    else
        rm -f "$CONFWEBDAV" "$CONFWEBDAVS" || ret=1
    fi
    if [ "$mport" != 0 ]; then
            gen_service "$ss" "$CONFPLAYER" || ret=1
    else
        rm -f "$CONFPLAYER" || ret=1
    fi
    if [ -n "$type_im" ] && \
        [ "$netapion" = "yes" -o "$netapion" = "true" -o "$netapion" = "on" ]; then
        gen_service "$ss" "$CONFIM" || ret=1
    else
        rm -f "$CONFIM" || ret=1
    fi

    return $ret
}

do_publish() {
    local RET

    if ! is_mounted "$SERVICESDIR"; then

        # remove any possibly remaining old config file (before they were volatile)
        rm -f "$CONFWEB" "$CONFWEBDAV" "$CONFWEBDAVS" "$CONFPLAYER" "$CONFIM"

        # mount volatile location
            echo -n "set up service dir"
        mount --bind "$VOLATILESERVICESDIR" "$SERVICESDIR"
            RET=$?
            if [ $RET -eq 0 ]; then
            echo -n ", "
            else
            failure; echo
            return 1
            fi

    fi

    echo -n "creating config"
    if [ "$ENABLE_MDNS_SERVICE_PUBLISH" = "yes" ]; then
            update_services
            RET=$?
    else
        # remove all service descriptions
        rm -f "$CONFWEB" "$CONFWEBDAV" "$CONFWEBDAVS" "$CONFPLAYER" "$CONFIM"
        RET=$?
    fi
    if [ $RET -eq 0 ]; then
        echo -n ", "
    else
        failure; echo
        return 1
    fi

    echo -n "reloading $BASENAME "
    if $DAEMON -c; then
        $DAEMON -r
        RET=$?
    else
        RET=0
    fi

    if [ $RET -eq 0 ]; then
        success; echo
    else
        failure; echo
    fi

    return $RET
}

start() {
    echo -n "Starting $DESC: "

    do_publish
}

reload() {
    echo -n "Reloading $DESC: "

    do_publish
}

stop() {
    local RET=0

    echo -n "Stopping $DESC: "

    if is_mounted "$SERVICESDIR"; then

        # mount volatile location
            echo -n "remove service dir"
        umount "$SERVICESDIR"
            RET=$?
            if [ $RET -eq 0 ]; then
            echo -n ", "
            else
            failure; echo
            return 1
            fi

        echo -n "reloading $BASENAME "
            if $DAEMON -c; then
            $DAEMON -r
            RET=$?
        else
            RET=0
        fi

    fi

    if [ $RET -eq 0 ]; then
        success; echo
    else
        failure; echo
    fi

    return $RET

}

parse() {
    case "$1" in
        start)
            start
            return $?
            ;;
        reload|force-reload)
            reload
            return $?
            ;;
        restart)
            return 0
            ;;
        stop)
            stop
            return $?
            ;;
        *)
            echo "Usage: $NAME {start|stop|restart|reload|force-reload}" >&2
            ;;
    esac
        
    return 1
}

parse $@

