import os
import os.path
import sys
import ssh
from createMD5 import main as createMD5

server = 'cmpdartsvr1.cmp.uea.ac.uk'
usr = 'red08xgu'
pss = 'Matura2000'
localDir = 'VolViewer/'
remoteDir = '/cmpdartsvr1/www/downloads/software/updates/Volviewer/win32/'

print "\n--------------------------------------------------------"
print "MD5: Computing local checksums..."
createMD5(localDir)
print "--------------------------------------------------------"
print "CONNECTING: " + server
s = ssh.Connection(host = server, username = usr, password = pss)
print "--------------------------------------------------------"
print "MD5: Retrieving remote checksums" 
remotefile = remoteDir + localDir + "md5checksums.txt"
locafile = "remote_md5checksums.txt"
s.get(remotefile,locafile)

localchecksums = "../md5checksums.txt"

#open the file with the checksums of files on the server
f = open(locafile, 'r')
for line in f:
	remotetokens = line.split("|")
	#open the file with the checksums of files on the local machine
	f2 = open(localchecksums, 'r')
	file_found = 0
	for line2 in f2:
		localtokens = line2.split("|")	
		localfile = localtokens[0].replace("../", localDir)
		
		#make sure we dont update the local checksum file
		if remotetokens[0] != localDir+"md5checksums.txt":
		
			#check if we are checking the same local/remote file pair
			if remotetokens[0] == localfile:
				file_found = 1
				
				#now check the checksum of the files
				#and if different get the file from the server
				if remotetokens[1] == localtokens[1]:
					print "File: " + localfile + " is up to date."
				else:
					print "Updating File: " + localfile
					s.get(remoteDir+remotetokens[0],localtokens[0])
	f2.close()
	
	#if we didn't find a file that exisits on the server
	#but not on the local machine, copy it to the local machine
	if file_found==0:
		if remotetokens[0] != localDir+"md5checksums.txt":
			localfile = remotetokens[0].replace(localDir, "../")
			print "NEW File: " + localfile
			s.get(remoteDir+remotetokens[0], localfile)

f.close()
os.remove(locafile)
print "--------------------------------------------------------"
print "FINISHED."
print "--------------------------------------------------------"

s.close()
