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

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

function converty() {
    [ -v enablesvc ] && enablesvc=y
    [ -v nolinger ] && nolinger=y
    [ "$runasuser" == "" ] && runasuser=$myuser
    assetdir="$assetdir/$runasuser"
}

# $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|connect-address|gui-address|gui-password|gui-user|homedir|nolinger|release|runasuser|runwait|sendstats|"
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" || exit
    plugin_printkeys
    converty
    # Add the release PGP keys:
    mkdir -p /etc/apt/keyrings
    notfirst=0
    if [ ! -f $SDMPT/etc/apt/keyrings/syncthing-archive-keyring.gpg ]
    then
	logtoboth "> Plugin $pfx: Download syncthing release key"
	curl -L https://syncthing.net/release-key.gpg -o $SDMPT/etc/apt/keyrings/syncthing-archive-keyring.gpg
    else
	[ "$(compgen -G "$SDMPT/etc/sdm/assets/syncthing/*")" != "" ] && notfirst=1
    fi
    mkdir -p $assetdir
    if [ $notfirst -eq 1 ]
    then
	[ "$gui__address" == "" ] && logtobothex "? Plugin $pfx: User '$runasuser' is not the first user; argument 'gui-address' is required"
	[ "$connect__address" == "" ] && logtobothex "? Plugin $pfx: User '$runasuser' is not the first user; argument 'connect-address' is required"
    fi
    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"
    converty
    [ "$release" == "" ] && release=stable
    #logfreespace "at start of Plugin $pfx Phase 1"
    if [ ! -f /etc/apt/sources.list.d/syncthing.list ]
    then
	logtoboth "> Plugin $pfx: Add syncthing release '$release' to apt sources"
	echo "deb [signed-by=/etc/apt/keyrings/syncthing-archive-keyring.gpg] https://apt.syncthing.net/ syncthing $release" > /etc/apt/sources.list.d/syncthing.list
	logtoboth "> Plugin $pfx: Perform apt update and install syncthing"
	doaptrpterror "update" $showapt
	installpkgsif syncthing
    fi
    #logfreespace "at end of $pfx Phase 1"
    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"
    converty
    [ "$runwait" == "" ] && runwait=3
    if [ "$homedir" == "" ]
    then
	[ "$runasuser" == "root" ] && homedir="/root" || homedir="/home/$runasuser"
    fi
    [[ "$gui__user" == "" ]] || [[ "$gui__password" == "" ]] && gui_user=""
    [ "$runasuser" == "" ] && logtobothex "? Plugin $pfx: No runasuser specified"
    [ "$(getent passwd $runasuser)" == "" ] && logtobothex "? Plugin $pfx: Unknown runasuser '$runasuser'"
    [ "$sendstats" == "" ] && sendstats=1
    logtoboth "> Plugin $pfx: Configure syncthing"
    logtoboth "  User: $runasuser"
    logtoboth "  Home Directory: $homedir"
    logtoboth "  Send Statistics: $sendstats"
    [ "$enablesvc" == "y" ] && s1="yes" || s1="no"
    logtoboth "  Enable syncthing user service: $s1"
    [ "$nolinger" == "y" ] && s1="no" || s1="yes"
    [ "$enablesvc" == "y" ] && logtoboth "  Start syncthing user service at boot: $s1"
    #logfreespace "at start of Plugin $pfx Phase post-install"
    if [ ! -f /etc/sysctl.d/062-syncthing-receive-buffer-size.conf ]
    then
	logtoboth "> Plugin $pfx: Configure sysctl to increase UDP receive buffer size"
	echo "net.core.rmem_max=7500000" >  /etc/sysctl.d/062-syncthing-receive-buffer-size.conf
	echo "net.core.wmem_max=7500000" >> /etc/sysctl.d/062-syncthing-receive-buffer-size.conf
    fi

    logtoboth "> Plugin $pfx: Create sdm FirstBoot script for user '$runasuser' to complete syncthing configuration"
    [ "$gui__address" == "" ] && gui__address="127.0.0.1:8384"
    [ "$connect__address" != "" ] && [[ "${connect__address##*://}" == "$connect__address" ]] && connect__address="tcp://$connect__address"
    cat > $assetdir/cfgsyncthing <<EOF
#!/bin/bash
echo $"cfgsyncthing for user '$runasuser' Created: $(thisdate) Run: \$(date +"$datefmt")
"
mkdir -p $homedir/.local/state/syncthing
chmod 700 $homedir/.local $homedir/.local/state $homedir/.local/state/syncthing
cat > $homedir/.local/state/syncthing/config.xml <<ZEOF
<configuration version="37">
    <gui enabled="true" tls="false" debugging="false">
        <address>$gui__address</address>
    </gui>
</configuration>
ZEOF
chmod 600 $homedir/.local/state/syncthing/config.xml
# Get user's group and then chown .local subtree
IFS=":" read xuser xpw xuid gx rest <<< \$(getent passwd $runasuser)
chown -R $runasuser:\$gx $homedir/.local
# Generate full syncthing config.txt and configure gui-user/password
syncthing --generate $homedir/.local/state/syncthing
[ "$connect__address" != "" ] && sed -i "s#<listenAddress>default#<listenAddress>$connect__address#" $homedir/.local/state/syncthing/config.xml
# Update send stats accept in xml
sed -i "s/<urAccepted>0/<urAccepted>$sendstats/" $homedir/.local/state/syncthing/config.xml
[ "$gui__user" != "" ] && syncthing generate --gui-user "$gui__user" --gui-password "$gui__password"
EOF
    chmod 755 $assetdir/cfgsyncthing
    # Run syncthing configuration script at end of sdm FirstBoot
    cat > /etc/sdm/0piboot/098-enable-syncthing-$runasuser.sh <<EOF
#!/bin/bash
logger "sdm FirstBoot: Configure and Enable syncthing for user $runasuser"
# Use /tmp b/c runasuser can't read/write $assetdir
cp $assetdir/cfgsyncthing /tmp/cfgsyncthing-$runasuser
chmod 755 /tmp/cfgsyncthing-$runasuser
logger "sdm FirstBoot: Configure syncthing as user '$runasuser' using '$assetdir/cfgsyncthing'"
logger "               Log: $assetdir/cfgsyncthing-$runasuser.log"
su --login $runasuser /tmp/cfgsyncthing-$runasuser </dev/null >/tmp/cfgsyncthing-$runasuser.log 2>&1
mv /tmp/cfgsyncthing-$runasuser.log $assetdir
rm -f /tmp/cfgsyncthing-$runasuser  # be neat
#mkdir -p $homedir/.config/systemd/user/multi-user.target.wants
#IFS=":" read xuser xpw xuid gx rest <<< \$(getent passwd $runasuser)
#chown -R $runasuser:\$gx $homedir/.config
if [ "$nolinger" != "y" ]
then
    logger "sdm FirstBoot: Enable linger for user '$runasuser'"
    loginctl enable-linger $runasuser
fi
if [ "$enablesvc" == "y" ]
then
    logger "sdm FirstBoot: Enable syncthing user service for '$runasuser'"
    systemctl --machine "$runasuser@" --user enable syncthing
    #ln -s /usr/lib/systemd/user/syncthing.service $homedir/.config/systemd/user/multi-user.target.wants
fi
exit 0
EOF
    #
    #logfreespace "at end of $pfx Custom Phase post-install"
    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
