#!/bin/sh
# \
exec wish $0 $@

###
###
################################################################
###                                              ###############
###        Alvaro's Messenger - amsn             ###############
###                                              ###############
###       http://www.amsn-project.net            ###############
###     amsn-users@lists.sourceforge.net         ###############
###                                              ###############
################################################################
### airadier at users.sourceforge.net (airadier) ###############
### Universidad de Zaragoza                      ###############
### http://aim.homelinux.com                     ###############
################################################################
### grimaldo@panama.iaehv.nl (LordOfScripts)     ###############
### http://www.coralys.com/linux/                ###############
################################################################
### Original ccmsn                               ###############
### http://msn.CompuCreations.com/               ###############
### Dave Mifsud <dave at CompuCreations dot com> ###############
################################################################
###
###
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; version 2 of the License
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
###
###

rename exec ::tk::exec
proc exec { args } {
  set ::env(LC_ALL) $::LC_ALL
  if {[catch {eval [linsert $args 0 ::tk::exec]} ret ] } {
     set ::env(LC_ALL) "C"
     return -code error $ret
  } else {
     set ::env(LC_ALL) "C"
     return $ret
  }
}

if {[info exists ::env(LC_ALL)] } {
  set ::LC_ALL $::env(LC_ALL)
} else {
  set ::LC_ALL ""
}
set ::env(LC_ALL) "C"


############################################################
### Some global variables
############################################################
# variable rcversion so autoupdate has no problems, version is used to be easier for users
# rcversion major.minor.patch, patch is 91,92 for RC's and after a release we put .svn
# behind the version. Lower patch numbers can be used on branch for bugfix releases.
#
# So the following is the correct version -> rcversion mapping:
# version				rcversion
#	0.97				0.97
#	0.97.1b	(branch!)	0.97.00.svn
#	0.97.1				0.97.01
#	0.97.2b				0.97.01.svn
#	0.98b				0.97.90.svn
#	0.98rc1				0.97.91
#	0.98b (after rc1)	0.97.91.svn
#	0.98				0.98

set version "0.98.4"
set rcversion "0.98.04"
set date "12/05/2010"
set weburl "http://www.amsn-project.net"
set program_dir "."
set HOME ""
set HOME2 ""
# distributions can change vendor if they provide a patched version of amsn so we
# can filter out bug reports only occuring with a particular vendor
set vendor "aMSN"

#=======================================================================


############################################################
### Look if we are launched from a link
### and set the correct working dir
############################################################

#Fixed by Tomasz Nguyen
set program_dir [file dirname [info script]]
set program [file tail [info script]]

while {[catch {file readlink [file join $program_dir $program]} program]== 0} {
	if {[file pathtype $program] == "absolute"} {
		set program_dir [file dirname $program]
	} else {
		set program_dir [file join $program_dir [file dirname $program]]
	}

	set program [file tail $program]
}

set starting_dir [pwd]
cd $program_dir
set program_dir [pwd]
unset program
#unset program_dir

set CERT_DIR [file join $program_dir ca-certs]

############################################################
### From here we need amsncore, for platform checks etc
###  so we load it.  Don't use anything that depends on 
###  utils packages yet though!
############################################################

source amsncore.tcl

############################################################
### Setup other important directory paths
### depending on the platform
############################################################

if { [OnDarwin] } {
   set HOME "[file join $env(HOME) Library/Application\ Support/amsn]"
} elseif { [OnUnix] } {
   set HOME "[file join $env(HOME) .amsn]"
} elseif { [OnWin] } {
  if {[info exists env(USERPROFILE)]} {
     set HOME "[file join $env(USERPROFILE) amsn]"
  } else {
   set HOME "[file join [pwd] amsn_config]"
  }
} else {
   set HOME "[file join [pwd] amsn_config]"
}
set HOME2 $HOME

############################################################
### Try to load tk and make sure tcl/tk is new enough for us
############################################################
package require Tk

if {$::tcl_version < 8.5} {
	wm state . withdrawn

	# Dummy functions required by sourcing sxml/lang/config.tcl
	set initialize_amsn 1
	proc status_log {args} {}
	proc load_my_pic {args} {}
	proc Showhidemenu {args} {}
	proc LoadStateList {args} {}
	namespace eval ::ChatWindow {
	    proc ShowHideChatWindowMenus {args} {}
	}
	namespace eval ::smiley {
	    proc cleanup {args} {}
	    proc parseMessageToList {args} {}
	}
	namespace eval ::plugins {
	    proc LoadPlugins {args} {}
	    proc calledFrom {args} {return -1}
	    proc PostEvent {args} {}
	}
	namespace eval ::skin {
	    proc reloadSkin {args} {}
	}

	# Load the required files for translations and user's lang config
	source sxml.tcl
	source lang.tcl
	source config.tcl

	tk_messageBox -default ok -message [trans upgradetcltk 8.5] -icon warning
	exit
}
#Q: can't this be done in 1 check like "[package require Tk] > 8.5" ?
#A: not on windows because you want any version of Tk to be loaded to show the messagebox


############################################################
### Hide the main window until it has been fully displayed
############################################################
wm state . withdrawn


############################################################
### And setup where to find optional packages
############################################################

proc lprepend {varName args} {
   upvar $varName var
   set var [eval [list linsert $var 0] $args]
}

lprepend auto_path [file join ${HOME} plugins]
#Specific folder to check for package on platforms
if { [OnDarwin] } {
	lprepend auto_path [file join utils macosx]
} elseif { [OnWin] } {
	lprepend auto_path [file join utils windows]
} elseif { [OnLinux] } {
	lprepend auto_path [file join utils linux]
} elseif { [OnBSD] } {
        lprepend auto_path [file join utils linux] 
}
lprepend auto_path [file join utils]

set libtls ""

catch { source [file join $HOME tlsconfig.tcl] }

if { $libtls != "" && [lsearch $auto_path $libtls] == -1 } {
    lprepend auto_path $libtls
}

#TODO: Move this from here ??
#///////////////////////////////////////////////////////////////////////
#Notebook Pages (Buddies,News,Calendar,etc.)
set pgBuddy ""
set pgNews  ""
#///////////////////////////////////////////////////////////////////////


############################################################
#### Load program modules
############################################################
set initialize_amsn 1

proc load_console {} {
	if { [info proc console] == "" && [info command console] == "" } {
		if { [file exists console.tcl] && [file readable console.tcl] } {
			uplevel \#0 {source console.tcl}
			console show
		}
	} else {
		console show
	}
}


proc reload_files { } {
    uplevel \#0 {

	# amsncore.tcl is already loaded but we'll re-source it here in case we manually do reload_files
	source amsncore.tcl
	source audio.tcl;	#audio API

	source ctthemes.tcl
	source progressbar.tcl	;# Progressbar Megawidget
	source migmd5.tcl
	source sxml.tcl   	;# Simple XML parser
	package require combobox 2.3
	source mutex.tcl
	source lang.tcl
	source automsg.tcl
	source smileys.tcl
	source skins.tcl	;# Used for skinning purposes
	source remote.tcl	;# The remote control procedures
	source assistant.tcl
	source chatwindow.tcl	;# Abstracted Chat Window code (::ChatWindow namespace)
	source picture.tcl ; #Tkcximage procs
	source login_screen.tcl ;# WLM style login screen
	source gui.tcl		;#gui.tcl must be at the beginning to make msg_box procedure available for errors
	source abook.tcl	;# Handle buddy address book    
	source protocol.tcl
	source proxy.tcl	;# loaded before plugins
	source msngames.tcl	;# game registering procedure must be available for plugins
	source plugins.tcl	;# Plugins system must be loaded before config
	source pluginslog.tcl
	source config.tcl	;# config needs to be loaded before pluginslog for translations
	source msnp2p.tcl
	source msncam.tcl
	source preferences.tcl
	source hotmail.tcl
	source groups.tcl	;# Handle buddy groups
	source pgu.tcl          ;# Parallel geturl
	source soap.tcl

	if { [OnDarwin] } {
		source [file join utils macosx applescript ae.tcl];#AppleEvent support
	}
	
	source alarm.tcl	;# Alarms code (Burger)
	source dock.tcl		;# Docking routines
	source trayicon.tcl	;# Docking routines for freedesktop system tray compliant docks
	source loging.tcl	;# Euh yeh it's for loging :P
	source searchdialog.tcl ;# Search dialog widget

	source balloon.tcl	;# For the balloons tooltip
	source autoupdate.tcl   ;# AUTOUPDATE!!!!!!!!!! :@
	
	source guicontactlist.tcl ;# New contact list (uses canvas)
	source bugs.tcl 	  ;# bug reporting
	source spaces.tcl         ;# MSN Space handling functions
	source auth.tcl           ;# MSNP15 SSO authentication mechanisms
	source addressbook.tcl    ;# MSNP15 contactlist handling functions
	source roaming.tcl    ;# MSNP15 Content Roaming functions
	source sip.tcl		  ;# Support for Audio conferencing with SIP and Farsight2
    }
    #As we reloaded amsncore, the version has been resetted and maybe amsn is the newest file
    ::Version::setSubversionId {$Id: amsn 12257 2010-12-05 03:23:14Z vivia $}
}

proc after_info { } {
	foreach f [after info] {
		status_log "After $f : [after info $f]\n" red
	}
}

reload_files

#Try to use async resolve if available
catch { package require asyncresolver }

set initialize_amsn 0
#///////////////////////////////////////////////////////////////////////

if { [catch {package require tls}] } {
    # Either tls is not installed, or $auto_path does not point to it.
    # Should now never happen; the check for the presence of tls is made
    # before this point.
#    status_log "Could not find the package tls on this system.\n"
    set tlsinstalled 0
} else {
    set tlsinstalled 1
}

#create_dir $HOME
set log_dir "[file join ${HOME} logs]"
set webcam_dir "[file join ${HOME} webcam]"
create_dir $log_dir
create_dir $webcam_dir

NS create ns -stat d -server [split [::config::getKey start_ns_server] ":"]

set family [lindex [::config::getGlobalKey basefont] 0]
set size [lindex [::config::getGlobalKey basefont] 1]

::themes::Init
if { $family == "" } { set family "Helvetica"}
if { $size == "" } { set size "11"}

if {[::config::getGlobalKey dpi] > 0} {
	tk scaling [expr {[::config::getGlobalKey dpi] / 72.0}]
}

::amsn::initLook $family $size [::config::getKey backgroundcolor]
foreach font [font families] {
	set allfonts([string tolower $font]) $font
}

# Bye bye hidden files in file dialogs (works fine with Mac even without this).
if {[OnLinux]} {
	catch { tk_getOpenFile -w00t } ;# start file dialog with unknown option
	catch { set ::tk::dialog::file::showHiddenVar 0}
	catch { set ::tk::dialog::file::showHiddenBtn 1}
}

set ::auto_encoding [encoding system]

if { [::config::getKey encoding] != "auto" } {
  set_encoding [::config::getKey encoding]
}

cmsn_draw_main

bind all <KeyPress> "set idletime 0"

idleCheck

degt_protocol_win
degt_ns_command_win

#after 500 proc_ns
#after 750 proc_sb

if {$version != [::config::getGlobalKey last_client_version]} {
   ::amsn::aboutWindow
   catch {file delete [file join $HOME2 bugreport.amsn]}
   #Force to change to Lucida Grande 12 on OS X, just one time when we switch version
   if { [OnMac] } {
      ::config::setGlobalKey basefont [list {Lucida Grande} 12 normal]
      ::config::setKey browser "open \$url"
   }
}

update idletasks

init_dock

if {[::config::getKey startontray]} {
	if { $::systemtray_exist == 1 } {
		wm state . withdrawn
		set ishidden 1
	} else {
		wm state . iconic
	}
} else {
	wm state . normal
}

proc auto_login_argv { user } { 
   if { [winfo exists .main.loginscreen] } { 
    .main.loginscreen.user delete 0 end 
    .main.loginscreen.user insert 0 $user 
    .main.loginscreen UsernameEdited 
    after 1000 "::MSN::connect" 
  } 
} 
  
if { $argv != "" && [LoginList exists 0 $argv] } {
   after idle [list auto_login_argv $argv] 
} else {
   if { [::config::getKey autoconnect] == 1 && [::config::getKey save_password] == 1} {
     	after idle "::MSN::connect"
   }
}


if { [::config::getKey autocheckver] == 1 } {
    after idle [list ::autoupdate::check_version_silent]
}



vwait events

# DO NOT WRITE ANY CODE BELOW THESE LINESSSSSSSSSS FOR ANY CODE TO BE ADDED, WRITE IT BEFORE THE 'vwait events' BECAUSE THAT LINE HANGS THE SCRIPT THERE FOREVER...
