#!/bin/sh
# ----------------------------------------------------------------------
#\
exec tclsh "$0" "$*"
# ----------------------------------------------------------------------
# tclsh executes everything from here on...

if {[catch {package require Tclx}]} {
   proc kill {signal pid} {
      set status [catch {exec kill -$signal $pid} killOut]
   }
}

package require Itk

set installdir [file dirname [info script]]

proc cleanup {} {
   global uploadPID
   global downloadPID

   if {$uploadPID != 0} {
      kill 1 $uploadPID
      set uploadPID 0
   }
   if {$downloadPID != 0} {
      kill 1 $downloadPID
      set downloadPID 0
   }
}

proc exitProgram {} {
   set status [cleanup]
   exit
}

wm protocol . WM_DELETE_WINDOW {
   set status [cleanup]
}

set uploadPID 0
proc upload_button {} {
   global uploadPID
   global installdir

   if {$uploadPID != 0} {
      kill 1 $uploadPID
      set uploadPID 0
   }
   if {$uploadPID == 0} {
      set status [catch {exec [file join $installdir importfile] @USE_REMOTE@ > /dev/null &} uploadPID]
   }
}

set downloadPID 0
proc download_button {} {
   global downloadPID
   global installdir

   if {$downloadPID != 0} {
      kill 1 $downloadPID
      set downloadPID 0
   }
   if {$downloadPID == 0} {
      set types {
         {{All Files} * }
      }
      set localFile [tk_getOpenFile -multiple 0 -title "Select Download File" -filetypes $types]
      if {$localFile != ""} {
         set status [catch {exec [file join $installdir exportfile] $localFile &} downloadPID]
      }
   }
}

button .upbut   -text "Upload"   -command "upload_button"   -width 8
button .downbut -text "Download" -command "download_button" -width 8
button .exitbut -text "Exit"     -command "exitProgram"     -width 8

pack .upbut
pack .downbut
pack .exitbut
