#!/bin/bash
. /etc/kona/soundsystem.inc

trace initdesktop2-in
touch /etc/kona/initdesktop2

if [ ! -z "$(grep -i $kv/ /etc/kona/os-release)" ]; then
  if [ ! -f /etc/kona/touchpad ]; then
    synclient TouchpadOff=1
  else
    synclient TapButton1=1
    synclient VertEdgeScroll=1
  fi
  if [ -z "$(pgrep xfce4-panel)" ]; then
    if [ ! -z "$(pgrep lxsession)" ]; then
      xfce4-panel &
      trace "xfce4-panel start"
    fi
  else
    if [ ! -z "$(pgrep lxsession)" ]; then
      lx="$(pgrep lxsession)"
      xp="$(pgrep xfce4-panel)"
      if [ "$lx" -gt "$xp" ]; then
        kill "$xp"
        xfce4-panel &
        trace "xfce4-panel retart"
      fi
    else
      killall xfce4-panel
    fi
  fi
fi

/etc/kona/checkserver.sh

trace "initdesktop2-wait server ready"
count=0
while [ ! -f /etc/kona/initready ]; do
  sleep 1
  count=$(($count+1))
  if [ "$count" -gt 120 ] || [ -f /etc/kona/initready ]; then
    break
  fi
done
if [ "$count" -gt 120 ]; then
  zenity --error --title="System Error" --text="システムの初期化スクリプトに異常が発生しています\n自動修復を試みますが、再び同じメッセージが出るときは作者にご連絡ください" --no-wrap
  cp /etc/kona/initsystem.sh /usr/local/etc/kona/error-intsystem.sh
  if [ -x ~/update/initsystem.sh ]; then
    cp ~/update/initsystem.sh /etc/kona/initsystem-new.sh
    rm ~/update/initsystem.sh
  else
    wget https://simosnet.com/debian/packages/Konalinux/$kd/update/$kv/update-$(cat /etc/kona/version).tgz
    if [ -f update-$(cat /etc/kona/version).tgz ]; then
      tar xfz update-$(cat /etc/kona/version).tgz update/initsystem.sh
      if [ -x ~/update/intsystem.sh ]; then
        cp ~/update/initsystem.sh /etc/kona/initsystem-new.sh
      fi
      rm update-$(cat /etc/kona/version).tgz
    fi
  fi
fi

trace "initdesktop2-initdesktop call"
/etc/kona/initdesktop.sh

if [ ! -z "$(grep -i $kv/ /etc/kona/os-release)" ]; then
  lx="$(pgrep lxsession)"
  xp="$(pgrep xfce4-panel)"
  if [ -z "$xp" ] || [ "$lx" -gt "$xp" ]; then
    [ -z "$xp" ] || kill "$xp"
    xfce4-panel &
    trace "xfce4-panel retart"
  fi
  if [ -z "$(grep NotShowIn=LXDE ~/.config/autostart/plank.desktop)" ]; then
    if [ -z "$(pgrep plank)" ]; then
      plank &
      trace "plank restart"
    fi
  fi
fi
#if [ -z "$(pgrep fcitx5)" ]; then
#   fcitx5 -d
#  trace "fcitx5 restart"
#fi

rm /etc/kona/initdesktop2
trace initdesktop2-out
