#!/bin/bash
#
# This is an sdm plugin for: imon
#
# The plugin is called three times: for Phase 0, Phase 1, and post-install.
#

function loadparams() {
    source $SDMPT/etc/sdm/sdm-readparams
}

# $1 is the phase: "0", "1", or "post-install"
# $2 is the argument list: arg1=val1|arg2=val2|arg3=val3| ...
#
# Main code for the Plugin
#
phase=$1
pfx="$(basename $0)"     #For messages
args="$2"
loadparams

if [ "$phase" == "0" ]
then
    #
    # In Phase 0 all references to directories in the image must be preceded by $SDMPT
    #
    logtoboth "* Plugin $pfx: Start Phase 0"

    logtoboth "> Plugin $pfx: download imon from GitHub to /usr/local/bin/imon and set protection"
    curl -L https://raw.githubusercontent.com/gitbls/imon/main/imon -o $SDMPT/usr/local/bin/imon
    curl -L https://raw.githubusercontent.com/gitbls/imon/main/imon-configure -o $SDMPT/usr/local/bin/imon-configure
    curl -L https://raw.githubusercontent.com/gitbls/imon/main/imon-action.sample -o $SDMPT/usr/local/bin/imon-action.sample
    curl -L https://raw.githubusercontent.com/gitbls/imon/main/imon@.service -o $SDMPT/etc/systemd/system/imon@.service
    chmod 755 $SDMPT/usr/local/bin/{imon,imon-configure,imon-action.sample}

    logtoboth "* Plugin $pfx: Complete Phase 0"

elif [ "$phase" == "1" ]
then
    #
    # Phase 1 (in nspawn)
    #
    logtoboth "* Plugin $pfx: Start Phase 1"
    # Install pip (if needed) then create create venv and install icmplib and requests into it
    [ "$(type -p pip3)" == "" ] && logtoboth "> Plugin $pfx: Install python3-pip" && installpkgsif python3-pip
    logtoboth "> Plugin $pfx: Create venv /root/.imon-venv"
    python3 -m venv /root/.imon-venv
    logtoboth "> Plugin $pfx: install icmplib and requests with pip3 into venv: /root/.imon-venv"
    /root/.imon-venv/bin/pip3 install icmplib requests
    logtoboth "* Plugin $pfx: Complete Phase 1"
else
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"

    plugin_addnote ""
    plugin_addnote "*** imon service notes ***"
    plugin_addnote ""
    plugin_addnote " * Use 'sudo imon-configure' to configure imon's service parameters"
    plugin_addnote " * Then use 'sudo systemctl enable --now imon@instancename'"
    plugin_addnote "   where 'instancename' is the name you created in imon-configure"
    plugin_addnote ""
    plugin_addnote " * See /usr/local/bin/imon-action.sample for a sample imon action script"
    plugin_addnote "   to customize event actions"
    plugin_addnote ""
    plugin_addnote " * For complete details: https://github.com/gitbls/imon"
    plugin_addnote ""

    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
