#!/bin/bash

# From: https://github.com/OSInside/kiwi/blob/v9.23.20/kiwi/config/functions.sh
# Or: /usr/lib/python3.6/site-packages/kiwi/config/functions.sh (python3-kiwi package)
function baseUpdateSysConfig {
    # /.../
    # Update the contents of a sysconfig variable
    # ----
    local FILE=$1
    local VAR
    local VAL
    if [ -f "${FILE}" ];then
        VAR=$2
        VAL=$3
        eval sed -i "s'@^\($VAR=\).*\$@\1\\\"$VAL\\\"@'" "${FILE}"
    else
        echo "warning: config file $FILE not found"
    fi
}

checkRoot() {
    if [[ $UID != 0 ]]; then
        echo "This option requires sudo:"
        echo "sudo $0 $*"
        exit 1
    fi
}

prepare() {
    checkRoot
    baseUpdateSysConfig /etc/sysconfig/displaymanager DISPLAYMANAGER_AUTOLOGIN linux
    baseUpdateSysConfig /etc/sysconfig/windowmanager DEFAULT_WM openbox
    echo "kamarada-firstboot" >> /home/linux/.config/openbox/autostart
    chown linux:users /home/linux/.config/openbox/autostart
    echo "enabled=False" > /home/linux/.config/user-dirs.conf
    chown linux:users /home/linux/.config/user-dirs.conf
}

run() {
    mkdir -p ~/.config
    touch ~/.config/kamarada-firstboot
    while [ -e ~/.config/kamarada-firstboot ]
    do
        python3 /usr/share/kamarada-firstboot/kamarada-firstboot.py

        # Read text file
        # https://stackoverflow.com/a/10771857/1657502
        RESULT=$(<~/.config/kamarada-firstboot)

        # Split string
        # https://stackoverflow.com/a/1478245/1657502
        set -- junk $RESULT
        shift
        SELECTED_LANGUAGE=$1
        SELECTED_ACTION=$2

        case "$SELECTED_ACTION" in
            Try)
                rm ~/.config/kamarada-firstboot
                sudo $0 --try $SELECTED_LANGUAGE
                break
                ;;

            Install)
                LANG=$SELECTED_LANGUAGE QT_QPA_PLATFORMTHEME="gtk2" kdesu -c /usr/bin/calamares
                ;;

            Shutdown)
                sudo shutdown -h now
                break
                ;;

            Reboot)
                sudo reboot
                break
                ;;
        esac
    done
}

try() {
    checkRoot
    baseUpdateSysConfig /etc/sysconfig/windowmanager DEFAULT_WM gnome
    # Delete the last line of the file
    sed -i '$d' /home/linux/.config/openbox/autostart
    rm /home/linux/.config/user-dirs.conf

    SELECTED_LANGUAGE=$1
    /usr/sbin/kamarada-setup $SELECTED_LANGUAGE

    systemctl restart display-manager
}

case "$1" in
    --prepare)
        prepare
        ;;
    --try)
        try $2
        ;;
    *)
        run
        ;;
esac

