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

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

function checkargval() {
    # $1: argument
    # $2: value
    local arg=$1 val=$2

    [[ "yes|no" =~ "$val" ]] || logtobothex "? Plugin $pfx: Invalid value '$val' for argument '$arg'"
}

# $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
vldargs="|enablesvc|listen-address|password-authentication|port|" #"|list|of|valid|args|"
rqdargs=""                   # |list|of|required|args|or|nullstring|
assetdir="$SDMPT/etc/sdm/assets/$pfx"

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"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    plugin_printkeys
    [[ -v enablesvc ]] && [[ "$enablesvc" != "socket" ]] && checkargval "enablesvc" "$enablesvc"
    [ -v password__authentication ] && checkargval "password-authentication" "$password__authentication"
    logtoboth "* Plugin $pfx: Complete Phase 0"
elif [ "$phase" == "1" ]
then
    #
    # Phase 1 (in nspawn)
    #
    logtoboth "* Plugin $pfx: Start Phase 1"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"

    [ "$enablesvc" == "" ] && enablesvc=yes
    if [ "$enablesvc" == "yes" ]
    then
	sshd="service"
    else
	[ "$enablesvc" == "socket" ] && sshd="socket" || sshd="none"
    fi
    dosshsetup "$sshd" sshd
    #
    # Update sshd configuration based on inputs
    #
    # listen-address, password-authentication, port
    #
    cp /etc/ssh/sshd_config /etc/ssh/.sdm.sshd_config
    if [ "$listen__address" != "" ]
    then
	logtoboth "> Plugin $pfx: Set sshd ListenAddress to '$listen__address'"
	sed -i "/#ListenAddress ::.*$/a ListenAddress $listen__address" /etc/ssh/sshd_config
    fi
    if [ "$password__authentication" != "" ]
    then
	logtoboth "> Plugin $pfx: Set sshd PasswordAuthentication to '$password__authentication'"
	sed -i "/#PasswordAuthentication yes.*$/a PasswordAuthentication $password__authentication" /etc/ssh/sshd_config
    fi
    if [ "$port" != "" ]
    then
	logtoboth "> Plugin $pfx: Set sshd Port to '$port'"
	sed -i "/#Port 22/a Port $port" /etc/ssh/sshd_config
    fi
    logtoboth "* Plugin $pfx: Complete Phase 1"
elif [ "$phase" == "post-install" ]
then
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"
    plugin_getargs $pfx "$args" "$vldargs" "$rqdargs"
    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
