#! /usr/bin/env python
"""Download files from the WWW. 
The filename can be a date-expression. 
Default is today, but a different day can be passed via params.
This is useful to download the radio-programm for tomorrow."""
version = "Version 0.1 - Written by Christian Folini."

# This script was built from a template script-file. Therefore some of the subroutines might not be used ad all.
# This typically extends to the in-pipe as well.
# This unnecessary code can be removed without a problem.

import sys
import os
import getopt

import pipes
import string
import tempfile

import time

FALSE, TRUE = 0, -1

debug = FALSE		# CAVE: These options must be declared in the get_opts routine
verbose = FALSE         #       as being global. Otherwise options passed will not be set globally.
			#       The same is true for any other option that changed in the get_opts routine.

add = 0		# days to add to the date

def print_version ():
	print version

def usage ():
	print __doc__
	print
	print "usage: " + sys.argv[0] + " [OPTIONS] url local-filename"
	print
	print " -a --add          add N days to the current date"
	print " -d --debug        debug flag"
	print " -v --verbose      be verbose"
	print " -h --help         this screen"
	print " -u --usage        dito"
	print " -?                dito"
	print "    --version      print the version and quit"
	print ""
	print "Parameters can be passed into the url-string."
	print "Valid parameters are:"
	print "__YEAR__, __MONTH__, __DAY__, __WEEKDAY__"
	print "__WEEKDAY__ is the number of the day of the week. Sunday is 0."

def condition_print(condition, text1, text2):
	"""Print param1 and (if present) param2 under a given condition (true or false)."""
        if condition:
		if not text2:
                	print text1
		else:
			print text1,
			print text2

def dprint(text1, text2=''):
	"""If 'debug' is true, param1 and (if present) param2 are printed."""
	condition_print (debug, text1, text2)
	
def vprint(text1, text2=''):
	"""If 'verbose' is true, param1 and (if present) param2 are printed."""
	condition_print (verbose, text1, text2)

def pipe(command):
	"""A pipe command. Submit the shell-command and get the STDOUT."""
	tmpfile = tempfile.mktemp()
        p=pipes.Template()
	
        p.append(command, '--')
        file=p.open(tmpfile, 'w')
        file.close()
        
	file =open(tmpfile) 
	result = file.read()
	file.close()
	os.remove(tmpfile)
	
	return result


def get_opts():
	"""Get the options of the call. 
	CAVE: Do not forget to declare variables as 'globals' in this script"""

	global debug
	global verbose
	global add

	inpipe = ''
	if not sys.stdin.isatty(): # redirected from file or pipe
		inpipe = sys.stdin.read()[:-1]

	try:
		opts, args = getopt.getopt(sys.argv[1:], \
			'a:dhu?v', \
			['add=', 'debug', 'verbose', 'usage', 'help', 'version'])
    	except getopt.GetoptError:
        	# print help information and exit:
		usage()
		print
		print "Option/Parameter problem. Aborting."
        	sys.exit(2)

	for opt in opts:
		name=opt[0]
		arg=opt[1]
		if name == '-a' or name == '--add':
			try:
				add = int(arg)
				dprint("Set 'add' to: ", add)
			except:
				print "Argument to 'add' is not of type integer. Aborting."
				sys.exit()
		if name == '-d' or name == '--debug':
			debug = TRUE
		if name == '-v' or name == '--verbose':
			verbose = TRUE
		if name == '-h' or name == '-u' or name == '-?' \
			or name =='--help' or name == '--usage':
			usage()
			sys.exit()
		if name == '--version':
			print_version()
			sys.exit()
	
	dprint("Pipe into the programm: ", inpipe)
	dprint("Options of the call: ", opts)
	dprint("Arguments of the call: ", args)
	
	return inpipe, args

def replace(mystr):
	now = time.localtime()
	mydate = time.mktime([now[0], now[1], now[2] + add, now[3], now[4], now[5], now[6], now[7], now[8]])  # making a new time. This converts the 'add' correctly to the date, even Dec 31st + 1 results in a correct date -> jan 1st
	mydate_tuple = time.localtime(mydate)  # building a new tuple out of the date
	dprint("new tuple", mydate_tuple)
	mystr = string.replace(mystr, '__YEAR__', str(time.strftime("%Y", mydate_tuple)))
	mystr = string.replace(mystr, '__MONTH__', str(time.strftime("%m", mydate_tuple)))
	mystr = string.replace(mystr, '__DAY__', str(time.strftime("%d", mydate_tuple)))
	mystr = string.replace(mystr, '__WEEKDAY__', str(time.strftime("%w", mydate_tuple)))
	return mystr




def main(url, destfile):
	string = "wget " + url
	dprint("Download string: ", string)
	os.system(string)
	if os.path.basename(url) <> destfile:
		string = "mv " + os.path.basename(url) + " " + destfile
		dprint ("mv string: ", string)
		os.system(string)
			
if __name__ == '__main__':
	inpipe, args = get_opts()
	url = args[0]
	url = replace(url)
	if len(args) > 1:
		destfile = args[1]
	else:
		dprint("No destination file submitted. Using url-filename instead.")
		destfile = os.path.basename(url)
	
	main (url, destfile)
