#!/bin/sh
# script for live-settings

set -e

if [ -f /etc/default/distro ]; then
    . /etc/default/distro
fi

all_users_common_settings() {
    # we run all users settings
    if [ -f /usr/share/future-common-livesettings/all-users-settings ] ;then
        /usr/share/future-common-livesettings/all-users-settings
    fi
}

gen_adduser_conf() {
    sed -i 's/^DIR_MODE=.*/DIR_MODE=0700/' /etc/adduser.conf

    unset GROUPS
    for g in ${FLL_LIVE_USER_GROUPS}; do
        if getent group ${g} >/dev/null; then
            GROUPS="${GROUPS} ${g}"
        fi
    done

    sed -i -e 's/^#\?\(EXTRA_GROUPS=\).*/\1"'"${GROUPS# }"'"/' \
           -e 's/^#\?\(ADD_EXTRA_GROUPS=\).*/\11/' \
            /etc/adduser.conf
}

add_live_user() {
    adduser --gecos ${FLL_LIVE_USER} ${FLL_LIVE_USER} \
<< EOF
live
live
EOF
}

user_home_common_settings() {
    if [ -f /usr/share/future-common-livesettings/user-home-settings ] ;then
        su "${FLL_LIVE_USER}" -c /usr/share/future-common-livesettings/user-home-settings
    fi
}


hack_bashrc() {
    grep -s -q 'alias su' /home/${FLL_LIVE_USER}/.bashrc && return 0
    printf "\nalias su='sudo su'\n" \
        >> /home/${FLL_LIVE_USER}/.bashrc
    chown ${FLL_LIVE_USER} /home/${FLL_LIVE_USER}/.bashrc
}

setup_calamares() {
    mkdir -p /home/${FLL_LIVE_USER}/Desktop
    if [ -e /usr/share/applications/calamares.desktop ]; then
        cp -f /usr/share/applications/calamares.desktop /home/${FLL_LIVE_USER}/Desktop
        chmod +x /home/${FLL_LIVE_USER}/Desktop/calamares.desktop
    fi
}

chown_user_dir() {
    # central point setting the ownership of users home
    chown -R ${FLL_LIVE_USER} /home/${FLL_LIVE_USER}
}


case "$1" in
    configure)
    all_users_common_settings
    if [ -d /home/${FLL_LIVE_USER} ]; then
        echo "                                     "
        echo "*************************************"
        echo "                                     "
        echo " Something went terrible wrong:      "
        echo "  /home/$FLL_LIVE_USER exist!        "
        echo " That should not be, please check    "
        echo " involved packages and pyfll.        "
        echo " This dir must not be created by     "
        echo " somehow or somewhat - only adduser  "
        echo " should do so.                       "
        echo "                                     "
        echo "*************************************"
        echo "                                     "
        exit 1
    fi
    gen_adduser_conf
    add_live_user
    setup_calamares
    hack_bashrc
    user_home_common_settings
    chown_user_dir
    ;;
    *)
        echo "livesettings  called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac


exit 0
