#!/bin/sh

if [ "x$1" = "x" ]; then
   exit 0;
else
   if [ "x$1" = "x-switch" ]; then
     if [ "x$2" = "x" ]; then
       exit 0;
     fi;
     
     APP=$2
     RUN=NO
   
   else
     APP=$1
     RUN=YES
   fi; 
fi; 

WMCTRL=`which wmctrl 2> /dev/null`
if [ "x$WMCTRL" = "x" ]; then

  # wmctrl not installed
  if [ "x$RUN" = "xYES" ]; then
    killall $APP
    $APP 2> /dev/null &
    exit 0;
  fi; 
fi;


IAM=`id -u`
IS_RUN=`pgrep -u $IAM $APP|head -1` 

if [ "x$IS_RUN" = "x" ]; then

  # app not run yet
  if [ "x$RUN" = "xYES" ]; then
    $APP 2> /dev/null &
    exit 0;
  fi; 

else
  
  if [ "x$WMCTRL" != "x" ]; then
    WIN_ID=`wmctrl -l -p|grep $IS_RUN|cut -d ' ' -f 1`

    if [ "x$WIN_ID" = "x" ]; then

      # can not find app window, start it again
      if [ "x$RUN" = "xYES" ]; then
        killall $APP
        $APP 2> /dev/null &
      fi;

      exit 0;
    fi;

    wmctrl -i -a $WIN_ID
  fi;

fi; 
