#!/bin/bash

# .xinitrc : setup routine after initalize X.org

PWROFF="/tmp/.cocon.poweroff"


get_nm_connected() {
  timeout=90
  nm_connect_pass=0
  while [ -z "`LANG=C nmcli -m multiline dev | grep -v disconnected | grep connected`" -a $nm_connect_pass -eq 0 ]
  do
    timeout=`expr $timeout - 1`
    if [ $timeout -le 0 ];
    then
      nm_connect_pass=1

      # TODO : dialog
    fi
    sleep 1
  done
}

# opencocon-local startup
if [ -e /tmp/.cocon.cnf ];
then
  . /tmp/.cocon.cnf
fi

if [ -e /tmp/.cocon.cnf.part ];
then
  . /tmp/.cocon.cnf.part
fi


if [ -e $PWROFF ];
then
  rm $PWROFF
fi

# Default running on matchbox window manager
matchbox-window-manager -theme blondie -use_desktop_mode plain &
lxpanel &
nm-applet &


# Volume
if [ "$COCON_MUTE_MASTER_ON_BOOT" = "1" ];
then
  amixer set 'Master' 0%
else
  if [ -n "$COCON_MASTER_VOLUME" ];
  then
    amixer set 'Master' $COCON_MASTER_VOLUME%
  fi
fi

# Read auto-connection setting and run (TODO : Sepalate to another script)


# Keymap
if [ "$COCON_KBD_X_MODEL" ];
then
  SETXKB=" -model $COCON_KBD_X_MODEL "
fi

if [ "$COCON_KBD_X_LAYOUT" ];
then
  SETXKB="$SETXKB -layout $COCON_KBD_X_LAYOUT "
fi

if [ "$COCON_KBD_X_VARIANT" ];
then
  SETXKB="$SETXKB -variant $COCON_KBD_X_VARIANT "
fi

if [ "$SETXKB" ];
then
  setxkbmap $SETXKB
fi

# Check if connected by NetworkManager
#LANG=C nmcli -m multiline dev | grep -v disconnected | grep connected


# Auto VPN connection
# TODO : multiple protocol
if [ "$COCON_AUTOVPN" ];
then
  echo "============== AUTOVPN : $COCON_AUTOVPN"
  get_nm_connected
  case $COCON_AUTOVPN in
  se)
    lxterminal -e "/usr/bin/cocon-softether-launch connect"
    ;;
  esac
fi


# Auto connection
if [ "$COCON_AUTOCONNECT" ];
then
  echo "============== AUTOCONNECT : $COCON_AUTOCONNECT"
  get_nm_connected
  case $COCON_AUTOCONNECT in
  rdp)
    lxterminal -e /usr/bin/cocon-freerdp-launch
    ;;
  vnc)
    cocon-vnc-launch 
    ;;
  spice)
    cocon-spice-launch
    ;;
  www)
    cocon-caravan-launch
    ;;
  x)
    cocon-xephyr-launch
    ;;
  esac
fi

# Disconnect VPN
# Auto VPN connection
if [ "$COCON_AUTOVPN" ];
then
  echo "============== AUTOVPN (Disconnect) : $COCON_AUTOVPN"
  case $COCON_AUTOVPN in
  se)
    cocon-softether-launch hangup
    ;;
  esac
fi



# Poweroff Flag
if [ "$COCON_POWEROFF_AFTER_AUTOCONNECT" = "1" ];
then
  echo "============== Poweroff after AUTOCONNECT"
  touch $PWROFF
  exit 0
else
  # TODO : Disable Autoconnect settings!
  sleep 5
fi 



  # New mode menu
while :
do
  if [ -e $PWROFF ];
  then
    break
  fi
  lxterminal -e /usr/bin/cocon-menu-launch
done

# Power off runs on .profile!
