#!/bin/bash

# firefox su ubuntu 14 e' la versione circa 66 e parte immediatamente
# firefox su ubuntu 18 e' versione circa 100 e ci mette 5 secondi per partire
# chromium non funziona sul ubuntu 18, tantomeno su 14
# chromium su ubuntu 22 parte molto velocemente

cd /opt/euro-beta
 
# <command>
install_with_apt() \
{
  [ `which $1` ] && return 0
  
  TMPRUN=`mktemp`
  cat << EOF >$TMPRUN
#!/bin/bash
apt update
apt install $1 -y
EOF
  chmod +x $TMPRUN
  ./show_process_output -T "Installazione del browser" $TMPRUN 2>&1
  rm $TMPRUN
}

# <command>
install_chromium64() \
{
  [ -f "$1" ] && return 0
  
  CHROMIUM_REPOSITORY=https://github.com/ungoogled-software/ungoogled-chromium-portablelinux/releases/download/144.0.7559.109-1/ungoogled-chromium-144.0.7559.109-1-x86_64.AppImage
  
  TMPRUN=`mktemp`
  cat << EOF >$TMPRUN
#!/bin/bash
wget $CHROMIUM_REPOSITORY -O $1.tmp && mv -f $1.tmp $1 2>/dev/null
chmod +x $1
EOF
  chmod +x $TMPRUN
  ./show_process_output -T "Installazione del browser" $TMPRUN 2>&1
  rm $TMPRUN

}

# <window title> <command>
run() \
{
  TITLE="$1"
  {
    CURR_DESKTOP=`wmctrl -d | grep '*' | cut -d' ' -f 1`
    CURR_DESKTOP=$(( $CURR_DESKTOP + 0 ))
    wmctrl -s 2
    PARM=""
    if [ -n "$3" ]
    then
      PARM="'"$3"'"
    fi
#    su euro3g -c "unset XDG_RUNTIME_DIR; $2 $PARM" &
      $2

    FF=$!
    for ((i=0; i<20; i++))
    do
      sleep 0.1
      wmctrl -r "$TITLE" -t 2
      wmctrl -a "$TITLE"
    done
    wait $FF
    wmctrl -s $CURR_DESKTOP
  } &
}


OS_RELEASE=`lsb_release -a 2>/dev/null | grep Release | awk '{ print $2; }' | cut -d '.' -f 1`

if [ "$OS_RELEASE" -le 18 ]; then
  install_with_apt firefox
  TMP=/tmp/.firefox
  mkdir -p $TMP $TMP/cache $TMP/config $TMP/data $TMP/runtime
  chown -R euro3g:euro3g $TMP
  run 'Mozilla Firefox' \
  "sudo -u euro3g env \
    HOME=$TMP \
    XDG_CACHE_HOME=$TMP/cache \
    XDG_CONFIG_HOME=$TMP/config \
    XDG_DATA_HOME=$TMP/data \
    XDG_RUNTIME_DIR=$TMP/runtime \
    DISPLAY=:0 \
    XAUTHORITY=/home/euro3g/.Xauthority \
    firefox \
    -UILocale it-IT \
    -contentLocale it \
    --new-instance
  "


#  "sudo -u euro3g firefox -UILocale it-IT -contentLocale IT --new-instance " 
else
  CHROMIUM=/opt/euro-beta/chromium.appimage
  install_chromium64 $CHROMIUM

  RESOLUTION=$(xrandr | grep "current" | awk '{print $8}') # prende "1366x768"
  WIDTH=$(echo $RESOLUTION | cut -d'x' -f1)
  HEIGHT=$(echo $RESOLUTION | cut -d'x' -f2)

  run 'Chromium browser' \
    "sudo -u euro3g env \
      HOME=/opt/euro-beta \
      DISPLAY=:0 \
      XAUTHORITY=/opt/euro-beta/.Xauthority \
      XDG_RUNTIME_DIR=/run/user/0 \
       $CHROMIUM \
      --window-size=$WIDTH,$HEIGHT \
      --window-position=0,0 \
      --no-default-browser-check \
      --disable-infobars \
      --disable-crash-reporter \
      --database=/opt/euro-beta/chrome-crashpad \
      --no-first-run 
    "
 fi 



