#!/bin/bash

### BEGIN INIT INFO
# Provides:          exagear-guest-debian-8
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: autostarter for services in debian-8 ExaGear guest
# Description:       autostarter for services in debian-8 ExaGear guest
### END INIT INFO

#
# This script is an autostarter for services in debian-8 ExaGear guest.
#
# Copyright (c) 2018 "Elbrus Technologies" LLC. All rights reserved.
#
# This script comes with NO warranty, not even for MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#

. /etc/exagear-guest.conf

if [ "`runlevel`" == "unknown" ]
then
        if [ "`systemctl get-default`" == "graphical.target" ]
        then
                rlevel="5"
        else
                rlevel="2"
        fi
else
        rlevel=$(runlevel | awk "{ print \$2 }")
fi

runlevel_normal=${rlevel}

image_dir="/opt/exagear/images/debian-8/"
vpaths_list="${image_dir}/.exagear/vpaths-list"
ubt="/opt/exagear/bin/ubt_x32a32_al"

function update_upstart_configurations {
    rm -f $(grep -l ${EXAGEAR_GUEST_WRAP_MARKER} /etc/init/* | grep -v update-exagear)

    local init_dir="${image_dir}/etc/init/"

    for service in $(find "$init_dir" -mindepth 1 -maxdepth 1 -type f -name '*.conf' -print) ; do
	${image_dir}/.exagear/upstart-integration/upstart-service-converter $(basename $service .conf) || true
    done
}

function invoke_start {
    start-stop-daemon -b -S -x /opt/exagear/images/$EXAGEAR_IMAGE_NAME/.exagear/upstart-integration/app-converter-daemon $EXAGEAR_IMAGE_NAME /usr/share/applications
    if [ "$RUN_RCSCRIPTS_AT_START" == "Y" ] ; then
        local rcdir="rc${runlevel_normal}.d"
        for rc in $(find "${image_dir}/etc/${rcdir}/" -mindepth 1 -maxdepth 1 -type l -name 'S*' -printf '%P\n'); do
            echo "$rc"
            $ubt --path-prefix $image_dir --vpaths-list $vpaths_list -- /etc/${rcdir}/$rc "$@"
        done
    fi
}

function invoke_stop {
    start-stop-daemon  -K -x /opt/exagear/images/$EXAGEAR_IMAGE_NAME/.exagear/upstart-integration/app-converter-daemon $EXAGEAR_IMAGE_NAME /usr/share/applications
    if [ "$RUN_RCSCRIPTS_AT_START" == "Y" ] ; then
        local rcdir="rc${runlevel_stop}.d"
        for rc in $(find "${image_dir}/etc/${rcdir}/" -mindepth 1 -maxdepth 1 -type l -name 'K*' -printf '%P\n'); do
            echo "$rc"
            $ubt --path-prefix $image_dir --vpaths-list $vpaths_list -- /etc/${rcdir}/$rc "$@"
        done
    fi
}

function copy_crontab {
    local re_rule="$1"
    local added_username="$2"

    local re_comment='(^[[:space:]]*#)|(^[[:space:]]*$)'
    local re_envvar='^[[:alnum:]]+[[:space:]]*='

    while read; do
        local comment=
        local envvar=
        local rule=

        (echo "$REPLY" | grep -E "$re_comment" > /dev/null) && comment=y
        (echo "$REPLY" | grep -E "$re_envvar" > /dev/null) && envvar=y
        (echo "$REPLY" | grep -E "$re_rule" > /dev/null) && rule=y

        if [ "$comment" == "y" ] || [ "$envvar" == "y" ] ; then
            echo "$REPLY"
        else
            if [ "$rule" != "y" ]; then
                continue;
            fi

            local condition=`echo "$REPLY" | sed -re "s/($re_rule)(.*)/\1/"`
            local action=`echo "$REPLY" | sed -re "s/($re_rule)//"`

            local cmd=
            local stdin=`echo "$action" | grep -E -o '[^\\]%.*'`
            stdin=${stdin:1}

            if [ -z "$stdin" ] ; then
                cmd="$action"
            else
                cmd=${action:0:$((${#action} - ${#stdin}))}
            fi

            printf "%s %s $image_dir/.exagear/upstart_wrapper /bin/sh -c %q%s\n" "$condition" "$added_username" "$cmd" "$stdin"
        fi
    done
}

function copy_udev_rules {
    if [ -z "${EXAGEAR_GUEST_WRAP_FILENAME}" ]
    then
	return
    fi

    echo "Exagear: forwarding udev rules...";
    rm -f /etc/udev/rules.d/${EXAGEAR_GUEST_WRAP_FILENAME}*

    wrapper=$(echo "$image_dir/.exagear/upstart_wrapper" | sed 's/\//\\\//g')
    sed_expr="s/RUN(\+?\=)\"(.+)\"/RUN\1\"$wrapper \2\"/g"
    for it in $(ls $image_dir/etc/udev/rules.d/ 2>/dev/null); do
        sed -r "$sed_expr" \
            "$image_dir/etc/udev/rules.d/$it" \
	    > /etc/udev/rules.d/${EXAGEAR_GUEST_WRAP_FILENAME}_$it
    done
}

function update_crontabs {
    if [ -z "${EXAGEAR_GUEST_WRAP_FILENAME}" ]
    then
	return
    fi
    echo "Exagear: forwarding crontabs...";
    rm -f /etc/cron.d/${EXAGEAR_GUEST_WRAP_FILENAME}_*

    local re_rule_base='^([^[:space:]]+[[:space:]]+)'
    local re_rule_peruser="${re_rule_base}{5}"
    local re_rule_systemwide="${re_rule_base}{6}"

    copy_crontab "$re_rule_systemwide" "" < $image_dir/etc/crontab > /etc/cron.d/${EXAGEAR_GUEST_WRAP_FILENAME}_crontab_systemwide

    for it in $(ls $image_dir/etc/cron.d/ 2>/dev/null); do
	copy_crontab "$re_rule_systemwide" "" < $image_dir/etc/cron.d/$it > /etc/cron.d/${EXAGEAR_GUEST_WRAP_FILENAME}_$it
    done

    for it in $(ls $image_dir/var/spool/cron/crontabs 2>/dev/null); do
        copy_crontab "$re_rule_peruser" "$it" \
          < $image_dir/var/spool/cron/crontabs/$it \
	  > /etc/cron.d/${EXAGEAR_GUEST_WRAP_FILENAME}_peruser_$it
    done
}

function update_forwards {
    [ "$DELEGATE_CRONTABS_AUTOMATICALLY" = "Y" ] && update_crontabs
    [ "$DELEGATE_UDEV_RULES_AUTOMATICALLY" = "Y" ] && copy_udev_rules
    [ "$DELEGATE_RC_SCRIPTS_AUTOMATICALLY" = "Y" ] && update_upstart_configurations
}

case "$1" in
    start|force-reload|reload)
        invoke_start "$@"
        update_forwards
        ;;
    stop)
        invoke_stop "$@"
        ;;
    restart)
        invoke_stop stop
        invoke_start start
        update_forwards
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|force-reload|reload}"
        ;;
esac

exit 0
