#!/usr/bin/env python
# -*- coding: ascii -*-

###########################################################################
# clive, video extraction utility
# Copyright (C) 2007 Toni Gundogdu
#
# clive 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 0.1.2-1307 USA
###########################################################################

import sys
import os
import traceback

from cStringIO import StringIO

try:
	import urlgrabber
except ImportError:
	sys.stderr.write('error: module urlgrabber not found\n')
	raise SystemExit

from clive.opts import Options
from clive.nomad import Nomad

class Clive:
	def __init__(self):
		self.optparser = Options()
		(self.opts, self.args) = self.optparser.parse()

		sys.excepthook = self._exc_hook
		self.exit_value = 0

	def main(self):
		self.optparser.show(self._say)
		nomad = Nomad()
		nomad.run(self.opts, self.args, self._say)
	
	# Non-public

	def _say(self, text='\n', show_always=0, is_error=0, newline=1):
		if self.opts.verbose or show_always:
			std = ([sys.stdout, sys.stderr][is_error])
			std.write(self._cleanup_text(text, newline))

	def _cleanup_text(self, text, newline):
		text = text.rstrip('\r\n')
		if newline: text += '\n'
		return text

	def _exc_hook(self, type, value, tb):
		self.exit_val = 1

		if type == IOError:
			text = '\nerror: %s' % (value[1][1])
			self._say(text)
		elif type != EOFError and type != KeyboardInterrupt:
			text = '\nerror: %s (%s)' % (type, value)
			self._say(text, show_always=1)
			trace = StringIO()
			traceback.print_exception(type, value, tb, None, trace)
			print trace.getvalue()
		else:
			print # empty line

if __name__ == '__main__':
	c = Clive()
	c.main()
	sys.exit(c.exit_value)


