#!/bin/bash
#
# Copyright 2006, 2007 by
# Manuel Carrasco
#
# This file is part of the LookXP project, and may only be used, modified,
# and distributed under the terms of the LookXP project license,
# LICENSE.TXT.  By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
#
#             http://lxp.sourceforge.net

# Version: 0.1

case $LANG in
	es.*)
		KEYBOARD_LAYOUT="Distribución del teclado"
		SWITCH_DESKTOP="Cambiar de escritorio"
		;;
	gl.*)
		KEYBOARD_LAYOUT="Distribución do teclado"
		SWITCH_DESKTOP="Cambiar de escritorio"
		;;
	*)
		KEYBOARD_LAYOUT="Keyboard layout"
		SWITCH_DESKTOP="Switch desktop"
		;;
esac

PACKAGE=lxp-icewm
MENU_SCRIPT=lxp-menu-generator
KEYBOARD_SCRIPT=lxp-icewm-keyboards
SWITCH_SCRIPT=lxp-switch-desktop


[ -z "$DISPLAY" ] && echo "No display defined" >&2 && exit 1

## Supported desktops
DESKS="idesk xfdesktop nautilus kdesktop rox ROX-Filer pcmanfm"

## Gnome apps and icewm need this for showing fonts configured into gnome (gnome-font-properties)
## Find gnome-settings-daemon
GSD=gnome-settings-daemon
for i in \
      /usr/libexec/gnome-settings-daemon \
      /usr/bin/gnome-settings-daemon \
      /usr/lib/control-center/gnome-settings-daemon 
do
		[ -x $i ] && GSD=$i
done

XTERM="xterm -bg black -fg white -fn '-misc-fixed-bold-r-normal--13-120-75-75-c-70-iso8859-1'"
XTERM="xterm -bg black -fg white -fn '-misc-fixed-bold-r-normal--18-120-100-100-c-90-iso8859-1'"



## Looks for a command in the PATH
isInstalled() {
  [ -z "$1" ] && return 1
  H=`type -p "$1"`
  [ -n "$H" -a -x "$H" ] && return 0 || return 1
}
getLang() {
   L=`echo $LANG | cut -c 1-2 | tr [A-Z] [a-z]`
   [ -z "$L" ] && L=en
   echo "$L"
}

### Create a preferences file for the user
IcewmPreferences() {
   [ ! -d $HOME/.$PACKAGE ] && mkdir -p $HOME/.$PACKAGE
   if [ ! -f $HOME/.$PACKAGE/preferences ]
   then
        echo "LXP Creating $HOME/.$PACKAGE/preferences" >&2
	#D=`find /usr/share/icons/Human -type d``find /usr/share/pixmaps -type d`
	D=`find /usr/share/icons/Human -type d`
	D=$D:`find /usr/share/pixmaps -type d`
	D="/usr/share/pixmaps:/usr/share/icons:"`echo "$D" | tr "\n" ":" | tr ":" "\n" | sort -u | tr "\n" ":"`
	[ -d /proc/acpi/battery/BAT0 ] && B=1 || B=0
        if isInstalled Xdialog || isInstalled kdialog || isInstalled zenity
        then
             XD=1
        else
             XD=0
        fi
        [ -f /usr/share/$PACKAGE/preferences ] && cat /usr/share/$PACKAGE/preferences > $HOME/.$PACKAGE/preferences
        cat <<EOF > $HOME/.$PACKAGE/preferences
IconPath="$D"

WindowActionsSupported="mixvkzrt"
WinMenuItems="rmsnxickw"

WorkspaceNames=" 1 ", " 2 ", " 3 ", " 4 "
TimeFormat=" %H:%M "
DateFormat="%A, %d %B %Y"

ShowLogoutMenu=1
ShowLogoutSubMenu=0
ShowHelp=0
ShowWindowList=0
ShowAbout=1
ToolTipDelay=200

TaskBarShowWorkspaces=1
TaskBarShowWindows=1
TaskBarShowShowDesktopButton=1
TaskBarShowTray=1
TaskBarShowMixer=1
TaskBarShowAllWindows=0
TaskBarShowWindowIcons=1
TaskBarShowWindowListMenu=0
TaskBarShowCollapseButton=1

TaskBarShowMailboxStatus=0
#MailCommand="lxp-command --mail"
#NewMailCommand="lxp-command --mail"

TaskBarShowClock=1
ClockCommand="lxp-command --calendar"

TaskBarShowCPUStatus=1
CPUStatusCommand="lxp-command --cpu"

TaskBarShowNetStatus=0
NetStatusCommand="lxp-command --net"

TaskBarShowAPMStatus=$B
TaskBarShowAPMTime=1

ShowRun=$XD
RunCommand="lxp-command --run"

### LXP TODO create utility commands for these actions
#LockCommand="lxp-command --lok"
#OpenCommand="lxp-command --open"
#TerminalCommand="xterm -bg black -fg white"
#LogoutCommand=
#ShutdownCommand=
#RebootCommand
#NetStatusCommand="lxp-command --net"
#AddressBarCommand="lxp-command --bar"

TaskBarWorkspacesLeft=0
QuickSwitchVertical=0
QuickSwitchwSmallWindow=1
QuickSwitchMaxWidth=1
QuickSwitchFillSelection=1
MenuMouseTracking=1
TaskBarShowWindows=1 # 0/1
TaskBarShowAllWindows=0
TaskBarShowTray=1 # 0/1
MinimizeToDesktop=0
OpaqueMove=0

EOF
   fi
   if [ ! -f $HOME/.$PACKAGE/winoptions ]
   then
		[ -f /usr/share/$PACKAGE/winoptions ] && cat /usr/share/$PACKAGE/winoptions > $HOME/.$PACKAGE/winoptions
        cat <<EOF >> $HOME/.$PACKAGE/winoptions
### Desktops (xfdesktop, nautilus, kde)
gimp.icon: gimp
xfdesktop.ignoreWinList: 1
xfdesktop.ignoreTaskBar: 1
xfdesktop.ignoreQuickSwitch: 1
desktop_window.ignoreWinList: 1
desktop_window.ignoreTaskBar: 1
desktop_window.ignoreQuickSwitch: 1
kdesktop.ignoreWinList: 1
kdesktop.ignoreTaskBar: 1
kdesktop.ignoreQuickSwitch: 1
EOF
   fi
}
IcewmTheme() {
   if [ ! -f $HOME/.$PACKAGE/theme ]
   then
      echo "LXP Creating $HOME/.$PACKAGE/theme" >&2
      cat <<EOF >$HOME/.$PACKAGE/theme
Theme="MiniNoRojo-Elberg/default.theme"
#Theme="MiniNoAzul-Elberg/default.theme"
#Theme="MiniNoVerde-Elberg/default.theme"
EOF
   fi
}
IcewmRestart() {
   if [ ! -x $HOME/.$PACKAGE/restart ]
   then
       echo "LXP Creating $HOME/.$PACKAGE/restart script" >&2
       cat <<EOF >$HOME/.$PACKAGE/restart
#/bin/sh
killall -HUP idesk >/dev/null 2>&1
killall -HUP ${PACKAGE}tray >/dev/null 2>&1
killall -HUP ${PACKAGE}bg >/dev/null 2>&1
EOF
       chmod 750 $HOME/.$PACKAGE/restart
   fi
}
IcewmShutdown(){
   if [ ! -x $HOME/.$PACKAGE/shutdown ]
   then
       echo "LXP Creating $HOME/.$PACKAGE/shutdown script" >&2
       cat <<EOF >$HOME/.$PACKAGE/shutdown
#/bin/sh
killall -TERM gnome-settings-daemon xfce-mcs-manager gam_server
killall -TERM $DESKS
EOF
       chmod 750 $HOME/.$PACKAGE/shutdown
   fi
}
IcewmStartup() {
   isInstalled idesk || return
   if [ ! -x $HOME/.$PACKAGE/startup ]
   then
       echo "LXP Creating $HOME/.$PACKAGE/startup script" >&2
       cat <<EOF >$HOME/.$PACKAGE/startup
#!/bin/sh
sleep 1
DEF=\`cat ~/.$PACKAGE/.defaultdesktop 2>"$SWITCH_DESKTOP"/dev/null | tr -d " "\`
[ -n "\$DEF" ] && DES=\$DEF || DES=idesk
\$DES &
[ -n "$GSD" -a -x "$GSD" ] && "$GSD" &
## Añadido por Miguel para crear el ~/.lxp-icewm/startup al estilo minino
case $LANG in
    es*)
         escritorio_rox="minino-es"
    ;;
    gl*)
         escritorio_rox="minino-gl"
    ;;
      *)    # Other
         escritorio_rox="minino-en"
    ;;
esac

setxkbmap `cat ~/.lxp-icewm/.defaultkeyboard`
defaultdesktop=`cat ~/.lxp-icewm/.defaultdesktop`

case $defaultdesktop in
    rox)
         rox -p $escritorio_rox -t $escritorio_rox &
    ;;
    pcmanfm)
         pcmanfm &
    ;;
    none)    # Sin ná
         echo "Sin ná de ná"
    ;;
esac
## hasta aquí
EOF
       chmod 750 $HOME/.$PACKAGE/startup
   fi
}

### Create a menu for the user
IcewmMenu() {
   if [ ! -f $HOME/.$PACKAGE/menu ]
   then
       echo "LXP Creating $HOME/.$PACKAGE/menu" >&2
      #menuprog "Gnome" folder $PACKAGE-menu-gnome2 --list /usr/share/desktop-directories
      #menuprog "Aplications" folder $PACKAGE-menu-gnome2 --list /usr/share/applications
      #menuprog "Programs" folder lxp-menu-generator

       if isInstalled $PACKAGE-menu-gnome2; then
           [ ! -d "$GD" ] && GD=/usr/share/desktop-directories
           [ ! -d "$GD" ] && GD=/usr/share/gnome/vfolders
           D=""
           RD=$GD/Root.directory
           [ ! -f "$RD" ] && RD=/usr/share/desktop-directories/Root.directory
           [ -d "$GD" -a -f "$RD" ] && L=`getLang` && D=`grep "^Name\[$L\]" "$RD" | cut -d "=" -f2-100`
           [ -z "$D" ] && D="Applications"
           if [ -d "$GD" ]; then
               PRG="menuprog \"(Gnome) $"$SWITCH_DESKTOP"D\" folder $PACKAGE-menu-gnome2 --list $GD"
           elif [ -d "/usr/share/applications" ]; then
               PRG="menuprog \"$D\" folder $PACKAGE-menu-gnome2 --list /usr/share/applications"
           fi
       fi
       if isInstalled lxp-menu-generator; then
           PRGM="menuprog \"Programs\" folder $MENU_SCRIPT"
       fi
       cat <<EOF >$HOME/.$PACKAGE/menu
prog xterm xterm $XTERM
prog fte fte fte
prog xfe xfe xfe
separator
## prog Mozilla mozilla mozilla
prog Eclipse eclipse eclipse
prog Firefox firefox firefox
prog Thuderbird thunderbird thunderbird
prog AMSN amsn amsn
separator
prog Gimp gimp gimp
prog "OOffice Writer" ooo_writer oowriter
prog "OOffice Calc"   ooo_calc   oocalc
prog "OOffice Impress" ooo_draw  oodraw
separator
$PRG
$PRGM
EOF
   fi
}


### Create a right tool menu with a keyboard switcher for X
IcewmRightToolMenu() {
   if [ ! -f $HOME/.$PACKAGE/rightbar ]
   then
      echo "LXP Creating $HOME/.$PACKAGE/rightbar" >&2
      cat <<EOF >$HOME/.$PACKAGE/rightbar
menuprogreload "$KEYBOARD_LAYOUT" keyboard 3  $KEYBOARD_SCRIPT
menuprogreload "$SWITCH_DESKTOP"  desktop  3 $SWITCH_SCRIPT --menu
EOF
   fi
}

### Create a left tool menu
IcewmLeftToolMenu() {
   if [ ! -f $HOME/.$PACKAGE/toolbar ]
   then
      echo "LXP Creating $HOME/.$PACKAGE/toolbar" >&2
      cat <<EOF >$HOME/.$PACKAGE/toolbar
## prog Mozilla mozilla mozilla
prog Firefox firefox firefox
prog Thuderbird thunderbird thunderbird
prog AMSN amsn amsn
prog xfe xfe xfe
prog xterm xterm $XTERM
EOF
   fi
}

### Create idesk Configuration
DesktopConf() {
   WP=/usr/share/$PACKAGE/themes/LookXP-Human/wallpaper.png
   isInstalled idesk && if [ ! -f $HOME/.ideskrc ]
   then
      echo "LXP Creating $HOME/.ideskrc" >&2
      cat > $HOME/.ideskrc <<EOF
table Config
  FontName: tahoma
  FontSize: 10
  FontColor: #ffffff
  Locked: false
  HighContrast: true
  Transparency: 79
  Shadow: true
  ShadowColor: #000000
  ShadowX: 1
  ShadowY: 2
  Bold: false
  ClickDelay: 200
  IconSnap: true
  SnapWidth: 10
  SnapHeight: 10
  SnapOrigin: BottomRight
  SnapShadow: true
  SnapShadowTrans: 200
  CaptionOnHover: false
  Background.Source: /usr/share/wallpapers/
  CursorOver: LEFT_PTR
EOF
      if [ -f $WP ]
      then
         cat >> $HOME/.ideskrc <<EOF
  Background.File: $WP
  Background.Mode: Scale
EOF
      fi
      cat >> $HOME/.ideskrc <<EOF
end
table Actions
  Lock: control right doubleClk
  Reload: middle doubleClk
  Drag: left hold
  EndDrag: left singleClk
  Execute[0]: left doubleClk
  Execute[1]: right doubleClk
end
EOF
   fi

   [ ! -f "$WP" ] && return

   isInstalled xfdesktop && if [ ! -f ~/.config/xfce4/mcs_settings/desktop.xml ] 
   then
        echo "LXP Creating $HOME/.config/xfce4/mcs_settings/desktop.xml" >&2
	mkdir -p ~/.config/xfce4/mcs_settings
	cat <<EOF >~/.config/xfce4/mcs_settings/desktop.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mcs-option SYSTEM "mcs-option.dtd">
<mcs-option>
        <option name="imagepath_0_0" type="string" value="$WP"/>
</mcs-option>
EOF
   fi

   isInstalled nautilus && if [ ! -f ~/.gconf/desktop/gnome/background/%gconf.xml ]
   then
        echo "LXP Creating $HOME/.gconf/desktop/gnome/background/%gconf.xml" >&2
	mkdir -p ~/.gconf/desktop/gnome/background
	cat <<EOF > ~/.gconf/desktop/gnome/background/%gconf.xml
<?xml version="1.0"?>
<gconf>
        <entry name="picture_filename" mtime="1164968805" type="string">
                <stringvalue>$WP</stringvalue>
        </entry>
        <entry name="picture_options" mtime="1164968805" type="string">
                <stringvalue>stretched</stringvalue>
        </entry>
</gconf>
EOF
   fi

}

### Create launchers for idesk
DesktopLaunchers()  {
   [ ! -d $HOME/.idesktop ] && mkdir -p $HOME/.idesktop
   [ ! -d $HOME/Desktop ] && mkdir -p $HOME/Desktop

   ## Look for a default icon
   I=`(find /usr/share/icons -name "*default*.???"; find /usr/share/pixmaps -name "*default*.???")`
   for s in 48x48 32x32 16x16 .
   do
        [ -z "$iconDefault" ] && iconDefault=`echo "$I" | grep "$s" | head -1`
   done

   ## Create icons for standard applications installed
   for i in firefox thunderbird eclipse xterm gimp k3b xfe amsn
   do
       X=`type -p $i 2>/dev/null`
       if [ -x "$X" -a ! -f $HOME/.idesktop/$i.lnk ]
       then
		   [ "$i" = xterm ] && X="$XTERM"
           I=`(find /usr/share/icons -name "*$i*.???"; find /usr/share/pixmaps -name "*$i*.???")`
           if [ -n "$I" ]
           then
                iconApp=""
                for s in 48x48 32x32 16x16 .
                do
                    [ -z "$iconApp" ] && iconApp=`echo "$I" | tr " " "\n" | grep $s | head -1`
                done
                [ -z "$iconApp" ] && iconApp=$iconDefault
                if [ -n "$iconApp" ]
                thencat 
                   echo "LXP Created launcher for $i app [$X] ($iconApp)" >&2
                   cat <<___________________EOF >$HOME/.idesktop/$i.lnk
                     table Icon
                        Caption: $i
                        CaptionTip: $i
                        Command: $X
                        Icon: $iconApp
			Width: 48
			Height: 48
                      end
___________________EOF

                   cat <<___________________EOF >$HOME/Desktop/$i.desktop
[Desktop Entry]
Type=Application
Exec=$X
Icon=$iconApp
Terminal=false
Name=$i
GenericName=$i
Comment=
___________________EOF
               fi
           fi
       fi
   done
}

###
###
###
###
###
###   MAIN    ###
IcewmPreferences
IcewmTheme
IcewmMenu
IcewmRightToolMenu
IcewmLeftToolMenu

## Configure Desktops
DesktopConf
DesktopLaunchers

## Startup, Restart and Shutdown scripts
IcewmStartup
IcewmRestart
IcewmShutdown

## Normally dbus is launched by gdm. If not, this lauchs dbus
if [ -n "$1" -a "$1" = --with-dbus ]
then
    if [ -n "$GSD" -a -x "$GSD" ]
    then
        (sleep 4; $GSD) &
    fi
    exec /usr/bin/dbus-launch --exit-with-session $PACKAGE-session
fi

## Exec gnome-settings-daemon
if [ -n "$GSD" -a -x "$GSD" ] 
then
     $GSD &
     sleep 3
     kill -0 $! >/dev/null 2>&1 || exit
fi
## Exec argv[1] 
if [ -n "$1" ]
then
	B=`type "$1" | awk '{print $3}'`
	[ -n "$B" -a -x "$B" ] && exec "$B"
	exit
fi

## Exec icewm-session
exec $PACKAGE-session 
