#! /bin/bash

error=0; trap 'error=$(($?>$error?$?:$error))' ERR # save maximum error code

cp -RT $FAI/simplefiles/PARTICIPANT $target

$ROOTCMD dconf update

# Uncomment this to reinstall extensions
# (disabled by default to speed up softupdate):
# rm -rf $target/etc/skel/.vscode

# VS Code extensions
if [ ! -d $target/etc/skel/.vscode ]; then
    # To avoid running VS Code as root, run it as nobody instead.
    mkdir $target/etc/skel/.vscode
    chown nobody:nogroup $target/etc/skel/.vscode
    shopt -s nullglob
    for ext in $FAI/downloads/*.vsix; do
        # We can't access the config space inside ROOTCMD, so we copy the file to the target.
        cp "$ext" $target/tmp/ext.vsix
        $ROOTCMD runuser -u nobody -- code --user-data-dir=/tmp/vsc.tmp \
            --extensions-dir=/etc/skel/.vscode/extensions \
            --install-extension=/tmp/ext.vsix
    done
    chown -R root:root $target/etc/skel/.vscode
    rm -rf $target/tmp/vsc.tmp $target/tmp/ext.vsix
fi

# Install soi header
tar --overwrite -xf $FAI/downloads/soi-header.tar.gz -C $target/usr/local/include --strip-components=2 soi-header/include/

# Install codeblocks template
$target/bin/unzip -o $FAI/downloads/soi_template_codeblocks_ubuntu_RzdvSho.zip -d $target/usr/share/codeblocks/templates/wizard/
if ! grep -q '_T("soi")' $target/usr/share/codeblocks/templates/wizard/config.script ; then
    sed -i 's|// project wizards|RegisterWizard(wizProject,     _T("soi"),      _T("A SOI task"),   _T("Console"));|' $target/usr/share/codeblocks/templates/wizard/config.script
fi

# Add a default keyring to avoid a prompt to create one when launching Chromium
mkdir -p $target/etc/skel/.local/share/keyrings/
chmod og= $target/etc/skel/.local/share/keyrings/
echo -n "Default_keyring" > $target/etc/skel/.local/share/keyrings/default
cat > $target/etc/skel/.local/share/keyrings/Default_keyring.keyring << EOF
[keyring]
display-name=Default keyring
ctime=0
mtime=0
lock-on-idle=false
lock-after=false
EOF
chmod og= $target/etc/skel/.local/share/keyrings/Default_keyring.keyring

# add super user account
if [ -n "$SUPER_USER_NAME" ]; then
if ! $ROOTCMD getent passwd $SUPER_USER_NAME ; then
	$ROOTCMD adduser --disabled-login --gecos "$SUPER_USER_DISPLAYNAME" $SUPER_USER_NAME
	$ROOTCMD usermod -p "$SUPER_USER_PW" $SUPER_USER_NAME
	$ROOTCMD adduser $SUPER_USER_NAME sudo
fi
fi

# add participant account
if [ -n "$PARTICIPANT_USER_NAME" ]; then
if ! $ROOTCMD getent passwd $PARTICIPANT_USER_NAME ; then
	$ROOTCMD adduser --disabled-login --gecos "$PARTICIPANT_USER_NAME" $PARTICIPANT_USER_NAME
	$ROOTCMD usermod -p "$PARTICIPANT_USER_PW" $PARTICIPANT_USER_NAME
fi
fi

exit $error