#!/bin/bash

. /usr/lib/eole/ihm.sh
. /usr/lib/eole/utils.sh

only_root

USER="$(whoami)"
# Never rename ${USER_HOME} to ${HOME} or this script will fail ;-)
USER_HOME=$(getent passwd ${USER} | awk -F':' '{print $6}')
export XAUTHORITY="${USER_HOME}/.Xauthority"
XLOCK="/tmp/.X0-lock"
APP_NAME='firefox'
BROWSER="/usr/bin/$APP_NAME"
SNAP_BROWSER_FOLDER="${USER_HOME}/snap/${APP_NAME}/common"

SERVER="127.0.0.1:5000"
APP_URL="http://$SERVER/genconfig/?application"

COMMON_BROWSER_OPT="--private-window ${APP_URL}"
SSH_BROWSER_OPT="$COMMON_BROWSER_OPT --window-size=1024,768"
#APP_BROWSER_OPT="$COMMON_BROWSER_OPT --kiosk"
# contournement bug en mode kiok #33878
APP_BROWSER_OPT="$SSH_BROWSER_OPT"


function clean_temporary_files {
    rm -rf $SNAP_BROWSER_FOLDER/.{mozilla,cache}
}

function gen_config_already_running {
    local current_pid=$$
    local running_genconfig=$(pgrep -xf "((/bin/)?bash( .*)? )?(/usr/sbin/)?gen_config")
    if [ ! "$current_pid" = "$running_genconfig" ]; then
        return 0
    else
        return 1
    fi
}

if gen_config_already_running; then
        EchoRouge "Quelqu'un utilise gen_config en ce moment, il est impossible de lancer gen_config plusieurs fois en même temps."
        exit 1
fi

tcpcheck 1 $SERVER >/dev/null 2>&1
if [ "$?" = "1" ]; then
    EchoRouge "gen_config n'est pas joignable, veuillez consulter les journaux d'eoleflask pour en savoir plus :"
    EchoRouge "/var/log/eoleflask/eolegenconfig.log"
    EchoRouge "et relancer le service avec la commande 'service eoleflask start'"
    exit 1
fi

clean_temporary_files

if [ ! -x /snap/bin/firefox ];then
    EchoOrange "firefox n'est pas installé"
    echo "installation de firefox..."
    snap install firefox || exit 1
fi

if [ -n "$SSH_CLIENT" ];then
    # over SSH
    if [ ! -n "$DISPLAY" ];then
        EchoRouge "DISPLAY manquant. Activer l'option SSH: 'ForwardX11'"
        exit 1
    fi
    systemctl --user import-environment DISPLAY XAUTHORITY
    ${BROWSER} ${SSH_BROWSER_OPT}
elif [ -n "$DISPLAY" ]
then
    # X is already stated
    systemctl --user import-environment DISPLAY XAUTHORITY
    ${BROWSER} ${APP_BROWSER_OPT}
elif [ -e $XLOCK ]
then
    EchoRouge "Trop de serveur X demarre"
    exit 1
else
    # Console mode
    TMPF=$(mktemp -p /tmp)
    LOG_TMPF=$(mktemp -p /tmp)
    /bin/echo "
start_matchbox_after_firefox() {
    for i in \$(seq 0 30); do
        sleep .5
        if pgrep -f 'firefox.*-childID 4' > /dev/null
        then
          sleep .1
          break
        fi
    done
    /usr/bin/matchbox-window-manager -use_titlebar no -use_desktop_mode decorated &
}

/usr/bin/numlockx
setxkbmap fr
systemctl --user import-environment DISPLAY XAUTHORITY
start_matchbox_after_firefox &
${BROWSER} ${APP_BROWSER_OPT} >> $LOG_TMPF 2>&1
exit 0" > $TMPF
    chmod a+x $TMPF
    xinit $TMPF &> /dev/null
    cat $LOG_TMPF
    rm -f $TMPF $LOG_TMPF
fi
clean_temporary_files
exit 0
