;************************************************************************************
;
;Program Name:  FTP_request()
;
;************************************************************************************
;
;Project     :     Soho - Lasco - Eit
;Name        :     FTP_REQUEST
;Category    :     Widgets
;Syntax      :     FTP_request, files_s (list of selected files qualified to sub-dir of local)
;Restrictions:     None
;Side Effects:     Launches XMANAGER if not already running - Modal Widget
;Calls	     :     CHK_DIR()
;History     :     Written 14 Oct. 1996 - Jesse Bankman
;                          24 Mar. 1997 - add hidden password input
;Version     :     ver.1.0
;                  ver.1.1 24 Mar. 1997 bp
;
;
;Contact     :     JB, bankman@linax1.mpae.gwdg.de
;
;
;
;*************************************************************************************

;*****************************************
;Test_Permission(directory) FUNCTION
;*****************************************
;This function tests if the user has access priviledge to a directory
;and returns a 0 if permission is granted and 1 if permission is denied

FUNCTION Test_Permission, dir

;Use a shell command to test if the user has permission.  Use sh5
;under ultrix.

if(!version.os ne 'ultrix')then $
	spawn, ['test -d '+dir+' -a -w '+dir+' ;echo $?'],result, /sh $
    else $
	spawn, ['/bin/sh5 -c "test -d'+dir+' -a -w'+dir+' "echo $?'], $
	result, /sh

RETURN, fix(result(0))   ; convert result to int.

END

;************************************************
;WRT_ASCII() Procedure - Pro to write an ascii file
;************************************************

PRO wrt_ascii,file,table,files_handle
 n = N_ELEMENTS(table) 

 IF n LT 1 THEN RETURN 

HANDLE_VALUE, files_handle, files_s
;For i=0, n_elements(files_s)-1 do begin
;	files_s(i) = STRMID(files_s(i), 0, 12)
;EndFor
files_s = 'get ' + files_s

script = [	'#! /bin/csh -f', $
		'cd $IMAGES/level_05/960819/c1', $
		'ftp -nv <<% > ftpsortie', $
		'open ' + table(0), $
		'user ' + table(1) + ' ' + table(2), $
		'binary', $
		'cd /net/corona/cplex1/flight_data/level_05/', $
		files_s, $
		'close', $
		'%',$
		'chmod 600 *',$
		'# a lancer par at ' + table(3) + ' ftpc1'	]

n = N_ELEMENTS(script)
 
OPENW,out,file,/GET_LUN 
FOR i=0,n-1 DO BEGIN 
 PRINTF,out,script(i)
ENDFOR 
FREE_LUN,out 
 
RETURN 
END 

;************************************************
;w_whdr_ftp() Procedure - Pro to write an ascii file
;************************************************
;This procedure was written expecting files_s input
;from the whdrinfo1.pro program.  Files_s strings are
;therefore of an expected form.

PRO w_whdr_ftp,file,table,files_handle

 n = N_ELEMENTS(table)
 IF n LT 1 THEN RETURN 
HANDLE_VALUE, files_handle, files_s
 
nofi  = N_ELEMENTS(files_s)
subpath = STRARR(nofi)
filenames = STRARR(nofi)

For i=0, nofi-1 do begin
        sep = STR_SEP(files_s(i),'/')
        filenames(i) = sep(n_elements(sep)-1)
        subpath(i)   = STRMID(files_s(i),0,RSTRPOS(files_s(i),'/'))
EndFor

lpath = table(4)
sizelpath = strlen(lpath)

IF strmid(lpath, sizelpath-1,1) EQ '/' THEN BEGIN
lpath = strmid(lpath, 0, sizelpath-1)
ENDIF

rpath = table(5)
sizerpath = strlen(rpath)
;If strmid(rpath, sizerpath-1,1) EQ '/' THEN $
;rpath = strmid(rpath, 0, sizerpath-1)

;remote and local now have no trailing delimiter
;this is done because a leading delimiter is expected
;in the files list

filenames = 'get ' + filenames

get_script = STRARR(2*nofi)
  for i=0, nofi-1 do begin
	;get_script(3*i) = 'lcd ' + lpath + subpath(i)
	get_script(2*i)= 'cd ' + subpath(i)
	get_script(2*i+1)= filenames(i)
  endfor

script = [	'ftp -n ', $
		'lcd ' + table(4), $
		'open ' + table(0), $
		'user ' + table(1) + ' ' + table(2), $
		'binary', $
		'cd ' + table(5), $
		 get_script, $
		'close', $
		'bye']

n = N_ELEMENTS(script)

OPENW,out,file,/GET_LUN 
FOR i=0,n-1 DO BEGIN 
 PRINTF,out,script(i)
ENDFOR 
FREE_LUN,out 
 
cmd = 'chmod go-r '+file
spawn,cmd

RETURN 
END 


;************************************************************************
;Function Time_Test()
;************************************************************************
;Function tests if the string passed to it is of the correct form: hh:mm
;If not, it returns null ('') or the corrected string.  If so it returns
;the original string.

FUNCTION Time_Test, ttmp

;	CATCH, error_status
;	IF error_status NE 0 THEN BEGIN
;		PRINT, 'String Conversion Failed!'
;		ttmp = ''
;		h = -1
;		m = -1
;	ENDIF


	IF strlen(ttmp) NE 5 THEN ttmp='' ELSE BEGIN
				
				IF strmid(ttmp, 2, 1) NE ':' THEN strput, ttmp, ':', 2
				h = strmid(ttmp, 0, 2)
				m = strmid(ttmp, 3, 2)

;INSERT KLUGE HERE!
				IF h EQ '00' THEN h=0 ELSE BEGIN
						h = fix(h)
						IF h EQ 0 THEN RETURN, ''
						ENDELSE
				IF m EQ '00' THEN m=0 ELSE BEGIN
						m = fix(m)
						IF m EQ 0 THEN RETURN, ''
						ENDELSE		

				htest = 1
				mtest = 1
				  IF h LT 0 THEN htest=0 ELSE $
				  IF h GT 23 THEN htest=0
				  IF m LT 0 THEN mtest=0 ELSE $
				  IF m GT 59 THEN mtest=0

				IF htest NE 1 THEN ttmp='' ELSE BEGIN
					IF h LT 10 THEN BEGIN
					h = STRCOMPRESS(STRING(h), /REMOVE_ALL)
					h = '0'+h
					ENDIF ELSE h = STRCOMPRESS(STRING(h), /REMOVE_ALL)
				ENDELSE
				IF mtest NE 1 THEN ttmp='' ELSE BEGIN
					IF m LT 10 THEN BEGIN
					m = STRCOMPRESS(STRING(m), /REMOVE_ALL)
					m = '0'+m
					ENDIF ELSE m = STRCOMPRESS(STRING(m), /REMOVE_ALL)
				ENDELSE
					
			IF ttmp NE '' THEN ttmp = h +':'+m
			ENDELSE

RETURN, ttmp

END

;*************************
;FTP_request event manager
;*************************

PRO FTP_request_event, event

COMMON ftp,passwd

WIDGET_CONTROL, event.id, GET_UVALUE = button_value
WIDGET_CONTROL, event.top, GET_UVALUE = control


CASE button_value OF

          "HOST":     BEGIN
                      ;Get event returned and 
		      ;change Stored variable Value in table
			WIDGET_CONTROL, control.ht, GET_VALUE=htmp
			HANDLE_VALUE, control.table, table
			table(0) = htmp
			HANDLE_VALUE, control.table, table, /SET
			
                      END

          "USER":     BEGIN
                      ;Get event returned and 
		      ;change store variable Value in table
			WIDGET_CONTROL, control.ut, GET_VALUE=utmp
			HANDLE_VALUE, control.table, table
			table(1) = utmp
			HANDLE_VALUE, control.table, table, /SET
                      END

          "PWD":      BEGIN
                      ;Text Updates should be hidden - Get event
	              ;and change stored variable Value in table
                        
			WIDGET_CONTROL, control.pt, GET_VALUE=ptmp
	                passwd = passwd + strmid(ptmp(0),0,1)

                        tmp = ptmp(0)
                        for i=0,strlen(tmp) do strput,tmp,'*',i
                        WIDGET_CONTROL,control.pt, SET_VALUE=tmp

			;HANDLE_VALUE, control.table, table
			;table(2) = ptmp
                        ;table(2) = passwd

			;HANDLE_VALUE, control.table, table, /SET
                      END

          "TIMELIST": BEGIN
                      ;Get event index generated - compare with timelist 
		      ;and store this value in the table -  check for immediately

			HANDLE_VALUE, control.list, timelist
			ind = event.index

			IF timelist(ind) EQ timelist(0) THEN time_string='now' $
			ELSE time_string = timelist(ind)

			WIDGET_CONTROL, control.tw, SET_VALUE=time_string

			HANDLE_VALUE, control.table, table
			table(3) = time_string
			HANDLE_VALUE, control.table, table, /SET

                      END

	  "TIME":     BEGIN
			WIDGET_CONTROL, control.tw, GET_VALUE=ttmp

			;String Test hh:mm Set to 00 if fail
			IF ttmp(0) NE 'now' THEN ttmp = Time_Test(ttmp(0))
			IF ttmp(0) EQ '' then ttmp = '00:00'
			WIDGET_CONTROL, control.tw, SET_VALUE=ttmp
			HANDLE_VALUE, control.table, table
			table(3) = ttmp
			HANDLE_VALUE, control.table, table, /SET			
		      END

          "OK":       BEGIN

 		      ;Write table into file with wrt_ascii, 'ftp ' + text

		      ;First Update the table
			WIDGET_CONTROL, control.ht, GET_VALUE = ht
			WIDGET_CONTROL, control.ut, GET_VALUE = ut
			;WIDGET_CONTROL, control.pt, GET_VALUE = pt
			WIDGET_CONTROL, control.tw, GET_VALUE = tt
			WIDGET_CONTROL, control.lp, GET_VALUE = lp
			WIDGET_CONTROL, control.rp, GET_VALUE = rp

			IF tt(0) NE 'now' THEN $
			ttmp = Time_Test(tt(0)) ELSE ttmp = tt(0)	
				;ttmp = now, null, or string
			IF ttmp GT '' THEN BEGIN
			HANDLE_VALUE, control.table, table
			table(0)=ht
			table(1)=ut
			table(2)=passwd
			table(3)=ttmp
			table(5)=rp
			HANDLE_VALUE, control.table, table, /SET
	
			WIDGET_CONTROL, control.lp, GET_VALUE = path
			path = STRCOMPRESS(path(0),/REMOVE_ALL)
			IF STRMID(path, strlen(path)-1, 1) NE !delimiter THEN $
			path = path+!delimiter

			filename = path + 'ftp_request.txt'
;the ftp request file is written to local...  perhaps it would be better to write it to home.

			IF control.files_set EQ 0 THEN BEGIN
			w_whdr_ftp, filename, table, control.files_handle
				;msg = WIDGET_MESSAGE("just used w_whdr_ftp", /Information)
			launcher = 'at -k -m -f ' + filename + ' ' + table(3)  
;print, launcher
			spawn, launcher
			;spawn, 'chmod u=rwx ' + filename
;or you could delete the file now.  But leave it there for testing purposes at the moment.

			ENDIF ELSE BEGIN
			wrt_ascii, filename, table, control.files_handle
				;msg = WIDGET_MESSAGE("just used wrt_asc", /Information)
			ENDELSE

			;msg1 = 'FTP request written to file: ' + filename
			;msg = WIDGET_MESSAGE(msg1,/information)
			;HANDLE_VALUE, control.table, filename, /SET
					
			WIDGET_CONTROL, event.top, /DESTROY
			ENDIF ELSE BEGIN
				ttmp = '00:00'
				WIDGET_CONTROL, control.tw, SET_VALUE=ttmp
				HANDLE_VALUE, control.table, table
				table(3)= ttmp
				HANDLE_VALUE, control.table, table, /SET
				msg = WIDGET_MESSAGE('Time must be of form hh:mm, ex. 06:12.')
			ENDELSE
			
                      END

	  "LOCAL":    BEGIN
			;Test if local path exists.  Check if user had access.
			;1 if valid 0 otherwise
			
			WIDGET_CONTROL, control.lp, GET_VALUE = local_path
			HANDLE_VALUE, control.table, table

			local_path = STRCOMPRESS(local_path(0), /REMOVE_ALL) 
				IF strmid(local_path, strlen(local_path)-1,1) NE !delimiter THEN $ 
				local_path = local_path + !delimiter 
			test1 = chk_dir(local_path)
			IF test1 NE 1 THEN BEGIN
					tmp = local_path + ' is not a valid directory!'
					err = WIDGET_MESSAGE(tmp)
					WIDGET_CONTROL, control.lp, SET_VALUE = table(4)
			ENDIF ELSE BEGIN
			;0 if granted, 1 if denied
			test1 = Test_Permission(local_path)
				IF test1 NE 0 THEN BEGIN
						tmp = 'You do not have permission to write to: ' + local_path
						err = WIDGET_MESSAGE(tmp)
						WIDGET_CONTROL, control.lp, SET_VALUE = table(4)
				ENDIF ELSE BEGIN
						table(4) = local_path		
						HANDLE_VALUE, control.table, table, /SET
				ENDELSE
			ENDELSE	
	
		      END

	  "REMOTE":   BEGIN

		      END

	  "FILES":    BEGIN
		      files_s = pickfiles()
		      HANDLE_VALUE, control.files_handle, files_s, /SET
		      END

          "CANCEL":   BEGIN
                      WIDGET_CONTROL, event.top, /DESTROY
                      END

	  "HELP":     BEGIN
		      ;Insert a help file telling that the function
		      ;writes a file that will cause the system to execute an ftp.
			XDISPLAYFILE, " ", $
			Group = event.top, $
			TITLE = "FTP_request Help", $
			WIDTH = 55, $
			HEIGHT = 16, $
			TEXT = ["     This FTP widget allows the user to input",$
				"information for an ftp, and then saves that", $
				"information to the file: ftp_request.txt.  This",$
				"file can be found in the local directory.", $
				"The user is asked to enter a FTP host address,", $
				"a user name, and a password.  By clicking with", $
				"the mouse in the 'TIME' Field, the user may",$
				"input when the ftp request will be sent. Entries",$
				'should be of the form "hh:mm" where hh is an',$
				"hour value from 00 to 23 and mm is a minute",$
				"value from 00 to 59.  Alternately, a time",$
				"may be chosen from the 'TIME' field droplist.",$
				"Clicking 'OK' writes the ftp request to the",$
				"file and exists the program.  Clicking 'CANCEL'",$
				"exits the program without writing the request."]
		      END	

ENDCASE

END










;*******************************
;FTP_request program definition
;*******************************

PRO FTP_request, FILES=FILES, NRL=NRL, EOF=EOF

COMMON ftp,passwd

passwd = ''
get_files = 0		; A test variable.  0 = false.  Controls activation of unmapped FILES button and ascii writer. 1 = get them.

IF NOT KEYWORD_SET(FILES) THEN get_files=1 $
ELSE files_s = files
IF get_files EQ 1 THEN files_s = ''

;Initialize time list
listvalue = ['Immediatedly', '00:00', '01:00', '02:00', '03:00', '04:00', '05:00','06:00',$
	     '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00',$
	     '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00']

IF GETENV('WORK') EQ '' THEN default_remote_dir = GETENV('HOME') ELSE $
          default_local_dir = getenv('WORK')+!delimiter+getenv('USER')+!delimiter+'fits'

hosts = ['lasco6.nascom.nasa.gov','cronus.nrl.navy.mil']
remote_dir = ['/net/lasco6/data/fits/level_05','/net/corona/cplex1/flight/data/level_05']

; change local path to remote path in files_s

IF KEYWORD_SET(nrl) OR KEYWORD_SET(eof) THEN BEGIN
 IF NOT KEYWORD_SET(files) THEN RETURN

 for i=0,n_elements(files_s)-1 do begin
  part_path = str_sep(files_s(i),'/')
  ind = WHERE( part_path EQ 'level_05')
  files_s(i) = remote_dir(0) + '/' + part_path(ind(0)+1) + $
                               '/' + part_path(ind(0)+2) + $
                               '/' + part_path(ind(0)+3)
 endfor
ENDIF

default_remote_dir = remote_dir(0)

;Define the interface

FTP_base = WIDGET_BASE(/Column,/Frame,TITLE='FTP_request')

txt_base=  WIDGET_BASE(FTP_base,/Column,/Frame)
tb1=       WIDGET_BASE(txt_base,/ROW)
host_lbl=  WIDGET_LABEL(tb1, VALUE = 'Host:  ')
ht= 	   WIDGET_TEXT(tb1,/EDITABLE, XSIZE = 40, VALUE=hosts(0),UVALUE='HOST')  
tb2=       WIDGET_BASE(txt_base,/ROW)
usr_lbl=   WIDGET_LABEL(tb2, VALUE = 'User:  ')
ut= 	   WIDGET_TEXT(tb2,/EDITABLE, XSIZE=40, VALUE = 'igse', UVALUE='USER')                
tb3=       WIDGET_BASE(txt_base, /ROW)
pass_lbl=  WIDGET_LABEL(tb3, VALUE = 'Password:  ')
pt= 	   WIDGET_TEXT(tb3, /Editable, VALUE = '', UVALUE = 'PWD',/ALL_EVENTS)
file_base= WIDGET_BASE(tb3, MAP=get_files)
file_pck=  WIDGET_BUTTON(file_base, VALUE = '  Files  ', UVALUE = 'FILES')

path_base= WIDGET_BASE(FTP_base, /COLUMN, /FRAME)
lpath=	   CW_FIELD(path_base, /RETURN_EVENTS, XSIZE=30, TITLE=  'Local Directory:   ', VALUE = default_local_dir, UVALUE='LOCAL')
rpath=	   CW_FIELD(path_base, /RETURN_EVENTS, XSIZE=30, TITLE = 'Remote Directory:  ', VALUE = default_remote_dir,UVALUE='REMOTE')


time_base= WIDGET_BASE(FTP_base, /ROW, /FRAME)
time_lbl=  WIDGET_LABEL(time_base, VALUE='Time:  ')
tw=	   WIDGET_TEXT(time_base, /EDITABLE,XSIZE=10, VALUE = 'now',UVALUE='TIME')
twdrop=    WIDGET_DROPLIST(time_base, VALUE=listvalue, UVALUE='TIMELIST')


but_base=  WIDGET_BASE(FTP_base,/ROW, /FRAME)
ok=        WIDGET_BUTTON(but_base, VALUE ='     OK     ', UVALUE='OK')
cancel=    WIDGET_BUTTON(but_base, VALUE ='   Cancel   ', UVALUE='CANCEL')
help=	   WIDGET_BUTTON(but_base, VALUE ='    Help    ', UVALUE='HELP')

;realize the widget
WIDGET_CONTROL, FTP_base, /REALIZE

;create a handle that will be a table to hold the text strings for
;time, user, host, and password
table = HANDLE_CREATE()
list = HANDLE_CREATE(table)		;create a handle for the list.  Make table it's parent.
files_handle = Handle_Create(table)	;create a handle for the files_s list
HANDLE_VALUE, files_handle, files_s, /SET

;Create an anonymous array for Widget Control Values.
control = {ht:ht,$	;Host Text
	  ut:ut,$	;User Text
	  pt:pt,$	;Password Text
	  table:table,$	;Holds Handle id
	  list:list,$	;Handle id for List of times to send
	  files_handle:files_handle,$	;Handle for files
	  files_set:get_files,$         ;files_set value of 0 indicates files keyword was set, 1 -> not set
	  lp:lpath, $	;Local Path Widget id
	  rp:rpath, $   ;Remote Path Widget id
	  tw:tw}	;ID of the time text widget

;Place array in FTP_base Uservalue
WIDGET_CONTROL, FTP_base, SET_UVALUE=control

;Initialize the table
WIDGET_CONTROL, ht, GET_VALUE=htmp
WIDGET_CONTROL, ut, GET_VALUE=utmp
WIDGET_CONTROL, pt, GET_VALUE=ptmp
WIDGET_CONTROL, lpath, GET_VALUE=ltmp
WIDGET_CONTROL, rpath, GET_VALUE=rtmp

time = 'now' ; initialize a string to hold the time text
tmp = [htmp, utmp, ptmp, time, ltmp, rtmp]
HANDLE_VALUE, table, tmp,/SET

HANDLE_VALUE, list, listvalue, /SET


XManager, "FTP_request", FTP_base, Event_Handler = "FTP_request_event",/MODAL

;HANDLE_VALUE, table, filename
Handle_Free, table

END

