#!/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
###########################################################################

## The main script containing the program entry point

import sys
import os
import traceback

from cStringIO import StringIO

try:
	import urlgrabber
except ImportError:
	raise SystemExit('error: urlgrabber module not installed')

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

__all__ = ['Clive']


## The main program class
class Clive:

	## Constructor
	def __init__(self):
		sys.excepthook = self._exc_hook
		self.exit_value = 0

		self.optparser = Options()
		(self.opts, self.args) = self.optparser.parse()

	## The program entry point
	def main(self):
		self.optparser.show(self._say)
		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])
			if is_error and not text.startswith('error:'):
				text = 'error: ' + text
			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 != EOFError and type != KeyboardInterrupt:
			trace = StringIO()
			traceback.print_exception(type, value, tb, None, trace)
			print >> sys.stderr, 'error: %s' % trace.getvalue()
		else:
			print # empty line

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


