#!/bin/sh

os="$(cat "$__global/explorer/os")"
trigger_command=$(cat "$__object/parameter/trigger-command")

case "$os" in
    devuan)
        __file /etc/init.d/cdist-preos-trigger --owner root \
            --group root \
            --mode 755 \
            --source - << EOF
#!/bin/sh
# /etc/init.d/cdist-preos-trigger

### BEGIN INIT INFO
# Provides:          cdist-preos-trigger
# Required-Start:    \$all
# Required-Stop:
# Default-Start:     2 3 4 5 S
# Default-Stop:      0 1 6
# Short-Description: Execute cdist preos trigger command
# Description:       Execute cdist preos trigger commnad.
### END INIT INFO

case "\$1" in
    start)
        echo "Starting cdist-preos-trigger command"
        ${trigger_command} &
        ;;
    stop)
        # no-op
        ;;
    *)
        echo "Usage: /etc/init.d/cdist-preos-trigger {start|stop}"
        exit 1
        ;;
esac

exit 0
EOF
    ;;
    *)
        __file /etc/systemd/system/cdist-preos-trigger.service --owner root \
            --group root \
            --mode 644 \
            --source - << EOF
[Unit]
Description=preos trigger
Wants=network-online.target
After=network.target network-online.target

[Service]
Type=simple
Restart=no
# Broken systemd
ExecStartPre=/bin/sleep 5
ExecStart=${trigger_command}

[Install]
WantedBy=multi-user.target
EOF

        require="__file/etc/systemd/system/cdist-preos-trigger.service" \
            __start_on_boot cdist-preos-trigger
    ;;
esac

