#!/usr/bin/env python
'''
usage : 
'''
import optparse
import subprocess
import re
import os
import sys
from optparse import OptionParser
from execBash import execBash
import time

#----------------- global variable ----------------#
#ssh_mount_dir = "mnt/sshfs/external_sd/001ns"
ssh_mount_dir = "storage/sdcard1/001ns"
dest_hp_cifs = "/home/knxy/sdcard/external_sd/001ns/"
src_hp_mtp = "/run/user/knxy/gvfs/mtp:host=%5Busb%3A002%2C007%5D/SD\ card/001ns"
dest_hp = "/media/knxy/3965-6566/001ns/"
dest_pc ='/home/knxy/Insync/insidekenshare@gmail.com/001ns'
dest_pendrive='/media/knxy/PENDRIVE/001ns'
copyToDest = []
copyToSrc = []
deleteFromDest = []
header='''<!DOCTYPE html>
<html>
<head>
<script src="/home/knxy/confignewpc/jquery/jquery-1.10.1.min.js">
</script>
<script>
$(document).ready(function(){
	$(".btn_show").click(function(){
		var pos=$(this).attr("value")
		$(this).siblings("a").after("<img style='max-width: 300px' src='"+pos+"'>");
	});

	$(".btn_del").click(function(){
		$(this).siblings("img").remove();
	});

	$("#btn_remove").click(function(){
		$("img").remove();
	});
});
</script>
<style>
th {
 background-color: #EEEEEE;
 border: 1px solid #CCCCCC;
 color: #555555;
 padding: 8px;
 text-align: center;
}

table {
 border-collapse: collapse;
 border-spacing: 0;
}

td {
 border: 1px solid #CCCCCC;
 padding: 5px 10px;
 vertical-align: top;
}

caption {
 text-align: center;
 background-color: #EFEFEF;
 border: 1px solid #CCCCCC;
 border-bottom: none;
 font-weight: bold;
 padding: 5px;
}
</style>
</head>
<body>
<button id=btn_remove>clean</button>
%s
</body>
</html>'''

html_table='''
<table>
<caption>%s</caption>
<th>source(%s)</th>
<th>destination(%s)</th>%s
</table>
'''

#----------------- parseCmd() ----------------#
## parse the command line arguments
def parseCmd():
	usage = "usage: %prog [options] <startBranch>..<endBranch> <branch1> <branch2> [<branch3>]"
	parser = OptionParser(usage)   #when --help is used or when wrong opt
 	parser.add_option("-f", "--file", dest="filename",
            help="read data from FILENAME")  # default action="store", options.filename
	parser.add_option("-e", "--execute",
			action="store_true", dest="execute_cmd",
			help="execute the actual rsync")  # set options.list_file=True
	parser.add_option("-d", "--dest",
			action="store", type="string", dest="dest_dir",
			help="specify the destination directory")  # set options.list_file=True
	parser.add_option("-s", "--src",
			action="store", type="string", dest="src_dir",
			help="specify the source directory")  # set options.list_file=True
	parser.add_option("-p", "--handphone-src",
			action="store_true", dest="handphone_src",
			help="specify that source is handphone")  # set options.list_file=True
	parser.add_option("-m", "--samba-src",
			action="store_true", dest="samba_src",
			help="specify that source is samba")  # set options.list_file=True
	parser.add_option("-r", "--pendrive-dest",
			action="store_true", dest="pendrive_dest",
			help="specify that destination is pendrive")
	parser.add_option("-a", "--tablet-acer",
			action="store_true", dest="tablet_acer",
			help="rsync between acer tablet and pc")
	parser.add_option("-l", "--lenovo_hp_ssh",
			action="store_true", dest="lenovo_hp_ssh",
			help="rsync between acer tablet and pc")
	parser.add_option("-t", "--use_android_mtp",
			action="store_true", dest="use_android_mtp",
			help="use android mtp to rsync with pc")
	parser.add_option("--reverse",
			action="store_true", dest="reverse_src_dest",
			help="rsync pc with android")
	#parse_args(arg) arg (default) = sys.argv[1:]
	return parser.parse_args()  #options.filename, options.verbose..


#----------------- processResult() ----------------#
def processResult(result, src_dir, dest_dir):
	#print result
	#current_dir = os.getcwd()
	reg_obj_new = re.compile(r"(.)f(.)........ (.*)")
	reg_obj_del = re.compile(r"\*deleting *(.*)")
	for line in result.split('\n'):
		print line
		matched_line = reg_obj_new.match(line)
		if matched_line:
			if matched_line.group(1)=='>':
				#print matched_line.group(0)
				fn = "%s"+os.sep+matched_line.group(3)
				fn_src = fn % src_dir
				fn_dest = ""
				if matched_line.group(2)!='+':
					fn_dest = fn % dest_dir
				copyToDest.append([fn_src, fn_dest])
			#elif matched_line.group(1)=='<':
			#	print matched_line.group(0)
			#	CopyToSrc()
		else:
			matched_del = reg_obj_del.match(line)
			if matched_del:
				fn_d = dest_dir+os.sep+matched_del.group(1)
				deleteFromDest.append(fn_d)

	print "-"*80
	print("source directory : %s" % (src_dir))
	print("destination directory : %s" % (dest_dir))
	print "-"*80
	#print "\ncopyToDest list: "
	#print copyToDest
	#print "\ndeleteFromDest list: "
	#print deleteFromDest

	generateHtml(src_dir, dest_dir)


#----------------- processResult() ----------------#
def logToFile(result):
	f = open("%s%s%s%slog%s" % (os.path.expanduser("~"), os.sep,
		"001ns-sync-record", os.sep, time.time()), "w")
	f.write("%s" % result)
	f.close()

#----------------- processResult() ----------------#
def generateHtml(src_dir, dest_dir):
	###
	content1=""
	for file in copyToDest:
		content1+="<tr><td><button value='%s' class=btn_show>show</button>" % file[0]
		content1+="<button value='%s' class=btn_del>clean</button>" % file[0]
		content1+=os.path.dirname(file[0])+os.sep
		content1+="<a href='"+file[0]+"'>"+os.path.basename(file[0])+" </a></td>\n"
		content1+="<td><button value=%s>show</button>" % file[1]
		content1+=os.path.dirname(file[1])+os.sep
		content1+="<a href='"+file[1]+"'>"+os.path.basename(file[1])+" </a></td></tr>\n"
	table1=html_table % ("Copy to "+dest_dir, src_dir, dest_dir, content1)

	content2=""
	for file in deleteFromDest:
		content2+="<tr><td></td><td>"
		content2+="<button value='%s' class=btn_show>show</button>" % file
		content2+="<button value='%s' class=btn_del>clean</button>" % file
		content2+=os.path.dirname(file)+os.sep
		content2+="<a href='"+file+"'>"+os.path.basename(file)+" </a></td></tr>\n"
	table2 = html_table % \
			("Delete from destination "+dest_dir, src_dir, dest_dir, content2)

	## put all content together
	table=table1+"<br><br>"+table2
	content=header % (table)

	## open file to write
	f = open("delete.html", "w")
	f.write("%s" % content)
	f.close()

	execBash("chromium-browser delete.html")


#----------------- main() ----------------#
def main():
	(options, args) = parseCmd()

	cmd = 'rsync -rltgoDzrvi --no-perms --delete --size-only \
			--progress \
			--exclude=ns_talk/*** \
			--exclude=uploaded\ photo/*** \
			--exclude=Wendy\ g3\ 5\ Feb\ 2013.mp3 \
			--exclude="Product class 21 Feb 2013.mp3" \
			--exclude=friends.doc '

	if options.src_dir:
		src_dir = options.src_dir + os.sep
	elif options.handphone_src:
		src_dir = dest_hp + os.sep
	elif options.samba_src:
		src_dir = src_hp_cifs + os.sep
	elif options.use_android_mtp:
		src_dir = src_hp_mtp + os.sep
	else:
		## default is always sync from hp
		src_dir = dest_hp + os.sep


	if options.dest_dir:
		dest_dir = options.dest_dir + os.sep
	elif options.pendrive_dest:
		dest_dir = dest_pendrive + os.sep
		src_dir = dest_pc + os.sep
	elif options.lenovo_hp_ssh:
		cmd = cmd + " --rsh='ssh -p 2222' --modify-window=1 "
		src_dir = "192.168.0."+ os.environ.get("HP_IP")
		src_dir = src_dir + ":/" + ssh_mount_dir + os.sep
		dest_dir = dest_pc + os.sep
	elif options.tablet_acer:
		cmd = cmd + " --rsh='ssh -p 2222' --modify-window=1 "
		src_dir = dest_pc + os.sep
		dest_dir = "192.168.0.10:/mnt/external_sd/001ns" + os.sep
	else:
		## default is always sync to pc
		dest_dir = dest_pc + os.sep


	if options.execute_cmd:
		result = execBash(cmd+src_dir+" "+dest_dir, False, True)[0]
		logToFile(result)
	else:
		cmd = cmd+" --dry-run "
		result = execBash(cmd+src_dir+" "+dest_dir, False, True)[0]

	## special handling based on options ----
	if options.lenovo_hp_ssh:
		src_dir = os.environ.get("HOME")+"/"
		src_dir = src_dir + ssh_mount_dir

	## final handling based on options ----
	if options.reverse_src_dest:
		## reverse the source and destination
		temp = dest_dir
		dest_dir = src_dir
		src_dir = temp

	processResult(result, src_dir, dest_dir)

#----------------- standalone() ----------------#
## if standalone, i.e. called directly from shell
if __name__ == '__main__':
	main()

#----------------- reference() ----------------#
#print ("\033[1;31mWarning!! command (%s) not ended properly."
#		"exit status = %d\033[0m" %(cmd, p.returncode))

