#!/usr/bin/python
# canon_upload, COpyright (C) 2012, Stuart Pook
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# must work with python 2.5

from __future__ import with_statement

import os, subprocess, sys
import time
import optparse
def run(options):
	if options.ssh_add:
		status = subprocess.call(["ssh-add", "-l"])
		if status:
			status = subprocess.call(["ssh-add"])
			if status:
				if options.interactive:
					time.sleep(60)
				return "ssh-add failed " + str(status)
	src = os.path.expanduser("~/MyDocs/Canon-EOS400D/raw/")
	dest = options.remote + ":/export/ws/Canon-EOS400D"
	command = ["rsync",
		"--recursive",
		"--times",
		"--progress",
		"--protect-args",
		"--partial-dir=.rsync", 
		"--modify-window=1",
	]
	if options.slow:
		command.append("--bwlimit=20")
	command.extend([ src, dest ])
	if not options.interactive:
		subprocess.check_call(command)
		return 0
	else:
		while True:
			status = subprocess.call(command)
			if status:
				print command[0], "failed with status", status
			print "try again? ",
			reply = sys.stdin.readline()
			if not reply or reply[0] == "n":
				print "giving up because you said", reply
				time.sleep(3)
				if status:
					return "quit with status " + str(status)
				else:
					return 0

def main():
	parser = optparse.OptionParser()
	parser.add_option("-i", "--interactive", action="store_true", help="interactive mode", default=False)
	parser.add_option("-s", "--slow", action="store_true", help="limit bandwidth", default=False)
	parser.add_option("-S", "--ssh_add", action="store_true", help="run ssh add", default=False)
	parser.add_option("-r", "--remote", help="remote host", default="localhost")
	(options, args) = parser.parse_args()
	return run(options)

if __name__ == "__main__":
	sys.exit(main())
