#! /usr/bin/python
"""
#+
# NAME:
#	hafbfts_sync
# PURPOSE:
#	Synchronizes local mirror of HAFB skymaps with the
#	content of the directory containing skymaps to be
#	burned on DVD.
# CATEGORY:
#	smei/gen/python
# CALLING SEQUENCE:
#	hafbfts_sync.py <mirror> <destination> <file_list>
# INPUTS:
#	sys_argv	command line list sys.argv
#				contains the info to log into the ftp site
# OUTPUTS:
#	Updated <destination>
# CALLS:
# PROCEDURE:
# MODIFICATION HISTORY:
#	JUL-2004, Paul Hick (UCSD/CASS)
#-
"""
import os, sys

def hafbfts_sync( mdir, ddir, file_list ):

	say = 'hafbfts_sync, '

	# Files and times already on DVD

	map_time = []
	map_list = []

	far_list = (open(file_list,'r')).read()
	far_list = far_list.split('\n')

	for file in far_list:
		tmp = file.split( ' ' )

		if (os.path.splitext(tmp[0]))[1] == '.fit':

			map_list.append( tmp[0] )
			if len(tmp) == 1:
				map_time.append( 0 )
			else:
				map_time.append( int(tmp[1]) )

	# Files and times in mirror directory

	far_list = os.listdir( mdir )
	far_time = []
	for file in far_list:
		far_time.append( (os.stat( os.path.join(mdir, file) )).st_mtime )

	# Loop over all files in mirror directory

	for i in range( len(far_list) ):

		far  = far_list[i]
		near = far.lower()

		buf = (os.path.splitext(far))[1]

		if buf != '.FIT':			# Skip if not a Fits file
			print 'skip '+far
			continue

		near_file = os.path.join( ddir, near )

		# If file already exists in ddir with same time, skip it

		if os.path.exists( near_file ):
			if os.stat( near_file ).st_mtime == far_time[i]:
				continue

			print 'overwrite ', near

		# If file is already on DVD with same time, skip it

		if map_list.count( near ) != 0:

			# If there is more than one copy on DVD then only keep
			# the last (and most recent) copy.

			while map_list.count( near ) > 1:
				tmp = map_list.index( near )
				del map_list[ tmp ]
				del map_time[ tmp ]

			if map_time[ map_list.index( near ) ] == far_time[i]:
				continue

			print 'second copy ', near
			if map_time[ map_list.index( near ) ] == 0:
				print 'remove timeless', near, 'from', file_list 

		# Copy file. Preserve time stamps.

		far_file = os.path.join(mdir, far)
		sts = os.spawnlp(os.P_WAIT, 'cp','cp','-vpf', far_file, near_file)

	return

if __name__ == '__main__':

	name = (os.path.split(sys.argv[0]))[1]
	say = name+', '

	narg = len(sys.argv)

	if narg < 2:
		mdir = os.environ[ 'FTS_MIRROR' ]
	else:
		mdir = sys.argv[1]

	if not os.path.isdir(mdir):
		print say+'non-existent directory, '+mdir
		sys.exit()

	if narg < 3:
		ddir = os.environ[ 'FTS_DVD' ]
	else:
		ddir = sys.argv[2]

	if not os.path.isdir(ddir):
		print say+'non-existent directory, '+ddir
		sys.exit()

	if narg < 4:
		file_list = os.path.join( ddir, 'fts_dvd.txt' )
	else:
		file_list = sys.argv[3]

	if not os.path.exists(file_list):
		print say+'file does not exist:', file_list
		sys.exit()

	hafbfts_sync( mdir, ddir, file_list )

	print say+'========== ALL DONE =========='

	sys.exit()
