#!/bin/bash


appliance_action_select()
{
  ./sysmsg -display :0  "Euro3g - Setup remoto" 'Controllo delle postazioni raggiungibili, attendere' &
  MSG_PID=$!
cat > appliance_select.xml <<EOF
<xml>
  <title text=" Euro3G - Setup remoto ">
  </title>
EOF
  WG_IP_ADDR=`ip -4 addr show wg0 | grep -oP "(?<=inet ).*(?=/)"`
  WG13=`echo $WG_IP_ADDR | cut -d'.' -f1-3`
  WG4=`echo $WG_IP_ADDR | cut -d'.' -f4`
  for IP_BYTE in {1..10}
  do
    CLIP=$WG13"."$((16*($WG4/16)+$IP_BYTE))
    if ping -c2 -w3 $CLIP >/dev/null 2>&1
    then
      /opt/euro-beta/systools/update_eurodb_ip_addr $CLIP
      SYSTEM_NAME=`systools/get_eurodb_config_val ModemSystemName`
cat >> appliance_select.xml <<EOF
  <choice name="Collegamento a $SYSTEM_NAME" command="/opt/euro-beta/systools/update_eurodb_ip_addr $CLIP">
  </choice>
EOF

    fi
  done

cat >> appliance_select.xml <<EOF
  <choice name="Teleassistenza VPN" command="/opt/euro-beta/show_process_output -w 'Torna indietro' -T 'Collegamento VPN' /opt/euro-beta/systools/remote_server_connect">
  </choice>
  <choice name="Riavvio veloce" command="restart euro3g">
  </choice>
  <choice name="Verifica aggiornamenti" command="/opt/euro-beta/e3g_upgrade">
  </choice>
  <choice name="Spegnere il sistema" command="poweroff">
  </choice>
</xml>
EOF

  kill $MSG_PID
  /opt/euro-beta/systools/update_eurodb_ip_addr 127.0.0.1
  ./btn_choice appliance_select.xml
}

WIREGUARD_ACTIVE=0
VIRTUAL_APPLIANCE=0
cd /opt/euro-beta/
source systools/touch_lib

if [ -f /opt/euro-beta/e3g_setup_appliance -a -f /etc/wireguard/wg0.conf ]
then
  /opt/euro-beta/systools/update_eurodb_ip_addr 127.0.0.1
fi

if [ -f /opt/euro-beta/systools/distr/euro3g_standalone_system ]
then
##  this part should be run only on dedicated system
# Activate swap partition(s)
  for swpart in `fdisk -l | grep swap | cut -d' ' -f1`
  do
    swapon $swpart
  done
fi

SYSTEM_AUDIO_VOLUME=`systools/get_eurodb_config_val SystemAudioVolume`
if [ $(( $SYSTEM_AUDIO_VOLUME + 1 )) -lt 1 -o $(( $SYSTEM_AUDIO_VOLUME + 1 )) -gt 101 ]
then
  SYSTEM_AUDIO_VOLUME=100
fi
./systools/set_master_audio_volume $SYSTEM_AUDIO_VOLUME

if [ -x ./postinstall_script ]
then
    if [ -f ./postinstall_title ]
    then
      ./show_process_output -T "`cat ./postinstall_title`" ./postinstall_script
    else
      ./show_process_output ./postinstall_script
    fi
    rm -f ./postinstall_script 
    rm -f ./postinstall_title
fi

rm db_backup/*.sql

if [ -f db_init.sql.gz ]
then
  cp db_init.sql.gz eurotest.sql.gz
  systools/restore_db eurotest
  rm db_init.sql.gz
fi

if ! systools/db_check ; then
#  echo Backing up and repair DB
  systools/autobackup
  systools/db_repair
else
#  echo DB O.K. Backup in background
  systools/autobackup &
fi

source ./setlog

FIXED_ACCESS_CODE_FILE="/root/.nxac_fixed"

if [ -e "$FIXED_ACCESS_CODE_FILE" ]
then
  systools/remote_server_connect
fi

E3G_STYLE=""

echo `dpkg-query -W -f='${Version};${Package};${Maintainer}\n' | grep 'info@spintec.com' | grep 'euro3g' | cut -d';' -f1 | tr -d '\n'` > /opt/euro-beta/last_update.info
LAST_UPDATE=`cat /opt/euro-beta/last_update.info`
systools/set_eurodb_config_val "Euro3GLastUpdate" string "$LAST_UPDATE"
echo "$LAST_UPDATE -- "`cat /etc/issue | cut -d '\' -f1` > /var/www/html/stat/last_update 

if [ -f /opt/euro-beta/systools/distr/euro3g_standalone_system ]
then
##  this part should be run only on dedicated system

#brutal hack to add pairing support for VirtualWire
killall bluetooth-agent
bluetooth-agent 1234 &

(dmidecode | grep -q 'ASUS EXPERTCENTER AIO E1600WKA_E1600WKA') && (lspci | grep -q 'RTL8822CE 802.11ac') && rmmod rtw88_8822ce
(lspci | grep -q 'RTL8821AE 802.11ac') && (grep -q ' AER: PCIe Bus Error: ' /var/log/syslog) && rmmod rtl8821ae

E3G_ID=`timeout 2 /opt/euro-beta/systools/spinkey || echo demo`
hostname ${E3G_ID}.e3g.spintec.com
echo ${E3G_ID}.e3g.spintec.com > /etc/hostname

export DISPLAY=:0
export EURO_DISPLAY=:0

if `cat /proc/cmdline | grep -q "casper"` 
then
  if `cat /proc/cmdline | grep -q "xrandr_zoom"` 
  then 
    touch /opt/euro-beta/xrandr_scale
  else
    rm -f /opt/euro-beta/xrandr_scale
  fi
  if `cat /proc/cmdline | grep -q "widescreen"` 
  then
    cp installer/spintec_default_wide.sql.gz inst_init_db.sql.gz
    touch /opt/euro-beta/e3g_wide_screen
  else
    cp installer/spintec_default_normal.sql.gz inst_init_db.sql.gz
    rm -f /opt/euro-beta/e3g_wide_screen
  fi
fi

if `cat /proc/cmdline | grep -q "e3g_setup_ova"` 
then
  VIRTUAL_APPLIANCE=1
  ln -nsf /opt/euro-beta/setup86 /opt/euro-beta/e2gui_current
fi

if [ -f "inst_init_db.sql.gz" ]
then
  systools/autobackup 
  cp inst_init_db.sql.gz eurotest.sql.gz
  systools/restore_db eurotest
  rm inst_init_db.sql.gz
fi

APP_XRES=800
APP_YRES=600
if [ -f /opt/euro-beta/e3g_wide_screen ]
then
  APP_XRES=1366
  APP_YRES=768
  perl -p -i -e "s/SHAD_GEOM=\"800x600\"/SHAD_GEOM=\"1366x768\"/sg" /usr/NX/bin/nxserver
  if file e2gui_current | grep demo ; then
    ln -nsf /opt/euro-beta/e2gui_wide_demo /opt/euro-beta/e2gui_current
  else
    ln -nsf /opt/euro-beta/e2gui_wide /opt/euro-beta/e2gui_current
  fi
else
  perl -p -i -e "s/SHAD_GEOM=\"1366x768\"/SHAD_GEOM=\"800x600\"/sg" /usr/NX/bin/nxserver
  if file e2gui_current | grep demo ; then
    ln -nsf /opt/euro-beta/e2gui86_demo /opt/euro-beta/e2gui_current
  else
    ln -nsf /opt/euro-beta/e2gui86 /opt/euro-beta/e2gui_current
  fi
fi


if [ -f /opt/euro-beta/kitchen_printer_mode ]
then
  ln -nsf /opt/euro-beta/E3GKitchenOrderDisplay /opt/euro-beta/e2gui_current
fi

unset EURO3G_FORCED_HOST_ID

if [ -f /opt/euro-beta/e3g_setup_appliance ]
then
  EURO3G_FORCED_HOST_ID=`cat /opt/euro-beta/e3g_setup_appliance`
  export EURO3G_FORCED_HOST_ID
  VIRTUAL_APPLIANCE=1
#  /opt/euro-beta/systools/update_eurodb_ip_addr 127.0.0.1
  systemctl start wg-quick@wg0.service >/dev/null
  ln -nsf /opt/euro-beta/setup86 /opt/euro-beta/e2gui_current
  if ! systemctl is-active wg-quick@wg0.service >/dev/null
  then
    WIREGUARD_ACTIVE=0
    touch /tmp/e3g_setup_virtual_appliance
  else
    WIREGUARD_ACTIVE=1
    rm /tmp/e3g_setup_virtual_appliance
  fi
fi

if `cat /proc/cmdline | grep -q "casper"` 
then
  if `cat /proc/cmdline | grep -q "lubuntu_desktop"` 
  then
    service sddm start
  fi
  if `cat /proc/cmdline | grep -q "e3g_installer"` 
  then 
    openbox &
    killall -9 inputattach
    handle_touchscreen
    cd /opt/euro-beta/installer
    ./E3gCasperInstaller
    /sbin/poweroff
  fi
fi


XRANDR_CON=`xrandr --query | grep " connected " | sed 's/connected primary/connected/'`
XRANDR_DEV=`echo $XRANDR_CON | cut -d' ' -f1`
XRANDR_DEV_SEC=`xrandr --query | grep " connected " | sed 's/connected primary/connected/' |  cut -d' ' -f1 | tail -1`

#same image on other monitor
xrandr --output $XRANDR_DEV ${APP_XRES}x${APP_YRES} --output $XRANDR_DEV_SEC --scale-from ${APP_XRES}x${APP_YRES} --same-as $XRANDR_DEV

if [ -f /opt/euro-beta/xrandr_scale ]
then
  XRANDR_XRES=`echo $XRANDR_CON | cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f1`
  XRANDR_YRES=`echo $XRANDR_CON | cut -d' ' -f3 | cut -d'+' -f1 | cut -d'x' -f2`
  XRANDR_SCALE_X=`( echo scale=4 ; echo $APP_XRES/$XRANDR_XRES ) | bc`
  XRANDR_SCALE_Y=`( echo scale=4 ; echo $APP_YRES/$XRANDR_YRES ) | bc`
#  XRANDR_OFFSET_X=$(( ( XRANDR_XRES-800 ) / 2 ))
#  XRANDR_OFFSET_Y=$(( ( XRANDR_YRES-600 ) / 2 ))
else
  if [ ! -f /opt/euro-beta/e3g_wide_screen ]
  then
    for XRANDR_DEV in `xrandr --query | grep " connected " | sed 's/ connected.*//g'`
    do
      xrandr --output $XRANDR_DEV --mode "${APP_XRES}x${APP_YRES}" --dpi 72
    done
  fi
fi

XKB=`systools/get_eurodb_config_val XkbLayout char`
[ "$XKB" ] && setxkbmap $XKB

openbox &



xset -dpms s off
killall -9 inputattach
OLD_SYSTEM_UUID=`cat e3g_system_uuid`
CURR_SYSTEM_UUID=`dmidecode -s system-uuid`

if `cat /proc/cmdline | grep -q "casper"` 
then 
  OLD_SYSTEM_UUID=`dmidecode -s system-uuid`
  ifconfig eth0 192.168.160.128 up
  rm e3g_inputattach
fi

if [ "$OLD_SYSTEM_UUID" != "$CURR_SYSTEM_UUID" ]
then
  echo "$CURR_SYSTEM_UUID"> e3g_system_uuid
  rm e3g_inputattach
  rm -f /var/lib/setserial/autoserial.conf
  rm -f /etc/udev/rules.d/70-persistent-net.rules
  ./sysmsg "Rilevata nuova configurazione" "E' stata rilevata una nuova configurazione di sistema. Il sistema viene riavviato per riconfigurare la rete e porte seriali" & 
  sleep 10
  killall sysmsg
  sync
  reboot
  exit 0
fi

if `lsusb | grep -q "ID 1ddb:0001"` 
then 
  rmmod usbhid 2>&1 > /dev/null
  modprobe usbhid quirks=0x1ddb:0x1:0x40 2>&1 > /dev/null
fi

if [ "$VIRTUAL_APPLIANCE" -ne 1 ]
then
  handle_touchscreen
fi

if [ -f /opt/euro-beta/xrandr_scale ]
then
  for XRANDR_DEV in `xrandr --query | grep " connected " | sed 's/ connected.*//g'`
  do
    xrandr --output ${XRANDR_DEV} --mode "${XRANDR_XRES}x${XRANDR_YRES}" --dpi 72
    xrandr --output ${XRANDR_DEV} --scale 0${XRANDR_SCALE_X}x0${XRANDR_SCALE_Y} --dpi 72
  done
  E3G_GEOMETRY="-geometry ${APP_XRES}x${APP_YRES}+0+0"
fi

#E3G_GEOMETRY="-geometry 1366x768+0+0"

# to install touchmon
#     install_input_filter
#killall touchmon
#TOUCH_BEEP_ENABLED=`systools/get_eurodb_config_val TouchScreenBeep bool`
#if [ "A$TOUCH_BEEP_ENABLED" == "A1" ]
#then
##  TOUCH_EVDEV_LIST="  "`grep -i touch /var/log/Xorg.0.log | grep /dev/input | grep evdev | cut -d'"' -f2 | sort | uniq`
#  TOUCH_EVDEV_LIST=`search_touch_devices`
#  for TOUCH_EVDEV in $TOUCH_EVDEV_LIST
#  do 
#    if [ -n "$TOUCH_EVDEV" ]
#    then
#       ./touchmon $TOUCH_EVDEV &
#    fi
#  done
#fi



##  this part should be run only on dedicated system
else
## if installed as desktop package we should check if eurotest DB exists and if not try to create it

MYSQL_INIT_NEEDED=""
echo "use eurotest" | mysql -u euro3g -peuro3g 2>/dev/null || MYSQL_INIT_NEEDED="Y"
if [ -n "$MYSQL_INIT_NEEDED" ]
then
MYSQL_ROOT_PARMS=""
echo "show databases" | mysql -u root >/dev/null 2>&1 || MYSQL_ROOT_PARMS=" -p"
if [ -n "$MYSQL_ROOT_PARMS" ]
then
  MYSQL_ROOT_PARMS=" -p"`./sysinput "Creazione del database iniziale del Euro3G" "Inserire la password di root per MySQL DB Server" 2>&1`
fi
cat systools/distr/e3g_desktop_mysql_init.sql | mysql -u root $MYSQL_ROOT_PARMS
echo "select * from db_version" | mysql -u euro3g -peuro3g eurotest 2>/dev/null || ( cp db_backup/spintec_default_[0-9]*.sql.gz eurotest.sql.gz ; systools/restore_db eurotest )
MY_IP_NIBBLE=`ifconfig | sed 's/inet \([0-9]\)/inet addr:\1/' | grep 'inet.*:' | head -1 | cut -d':' -f2 | cut -d' ' -f1 | cut -d'.' -f4` 
echo "DELETE FROM user_keys WHERE host_id=$MY_IP_NIBBLE" | mysql -u euro3g -peuro3g eurotest
echo "UPDATE user_keys SET host_id=$MY_IP_NIBBLE WHERE host_id=128" | mysql -u euro3g -peuro3g eurotest
fi # MYSQL_INIT_NEEDED

E3G_STYLE="-style platinum"

## if installed as desktop package we should check if eurotest DB exists and if not try to create it
fi

if ! [ -f ./e3g_eula_accepted ]
then
  if ./ask_license 
  then
    touch ./e3g_eula_accepted 
  else
    if [ -f /opt/euro-beta/systools/distr/euro3g_standalone_system ]
    then
      /sbin/poweroff
    else
      exit 5
    fi
  fi
fi

if [ ! -f /opt/euro-beta/quick_restart ] ; then
  rm -f /opt/euro-beta/tmp_demo_mode
fi

rm -f /opt/euro-beta/quick_restart

if [ "$VIRTUAL_APPLIANCE" -eq 1 -a "$WIREGUARD_ACTIVE" -eq 1 ]
then
  appliance_action_select
  if grep -q '127.0.0.1' eurodb.ini
  then
    exit
  fi
fi

if [ -f /opt/euro-beta/tmp_demo_mode ] ; then
  if file e2gui_current | grep demo ; then
    ./e2gui_current $E3G_STYLE $E3G_GEOMETRY >> $E2GUI_LOG 2>&1
  else
    PATH=$PATH:. `file e2gui_current | sed 's/\x60//g; s/\x27//g' | cut -d ' ' -f 5`_demo $E3G_STYLE >> $E2GUI_LOG 2>&1
  fi
else
  ./e2gui_current $E3G_STYLE $E3G_GEOMETRY >> $E2GUI_LOG 2>&1
fi

if [ "$VIRTUAL_APPLIANCE" -eq 1 ]
then
#  /opt/euro-beta/systools/update_eurodb_ip_addr 127.0.0.1
  if [ "$WIREGUARD_ACTIVE" -ne 1 ]
  then
    poweroff
    sleep 20
  fi
fi


