#! /bin/sh
### BEGIN INIT INFO
# Provides:          create fake systemctl form service
# Required-Start:    mountkernfs $local_fs $network
# Required-Stop:
# Should-Start:      udev module-init-tools
# Default-Start:     S
# Default-Stop:
# Short-Description: Create a systemctl bash script to emulate systemctl
# Description:       In WSL2 windows systemctl may be not activated; in this case
#                    a bash script in /usr/local/bin active the required service with
#                    systemctl syntax. If systemctl runs, this script do nothing
### END INIT INFO
#

name_n_bin() {
    app="$1"
    a=$(which $app 2>/dev/null)
    [ -z "$a" ] && a="/usr/local/bin/$app"
    [ -x $a ] && m="$(file -b --mime-type $a)" || m=""
}

start() {
    STATUS=0
    grep -q "^systemd *= *true" /etc/wsl.conf && echo "systemctl active" && stop && return $STATUS
    name_n_bin "systemctl"
    if [ ! "$a" = "/usr/local/bin/systemctl" -o "$m" = "text/x-shellscript" ]; then
        a="/usr/local/bin/systemctl"
        echo "'systemctl' -> $a"
        echo "#! /bin/bash">$a
        echo "if [[ -f /etc/init.d/\$2 ]]; then">>$a
        echo "    service \$2 \$1">>$a
        echo "elif [[ \$1 =~ ^(start|stop|reload|restart|status)$ ]]; then">>$a
        echo "    echo \"Service \$2 not found!\"">>$a
        echo "else">>$a
        echo "    /usr/bin/systemctl \$1 \$2 \$3 \$4 \$5 \$6 \$7 \$8 \$9">>$a
        echo "fi">>$a
        chmod +x $a
    fi
    return $STATUS
}

status() {
    name_n_bin "systemctl"
    [ -x "$a" ] && echo "$app ($a $m) active .." || echo "$app NOT FOUND!"
    return 0
}

stop() {
    name_n_bin "systemctl"
    [ -x "$a" ] && [ "$m" = "text/x-shellscript" ] && echo "rm -f $a" && rm -f "$a"
    return 0
}


case "${1}" in
    start)
        start
        ;;

    status)
        status
        ;;

    stop)
        stop
        ;;

    *)
        echo "Usage: %0 {start|stop|status}" >&2
        exit 1
        ;;
esac
