#! /usr/bin/env python

"""
Update all fink packages, except those in an excluded list.

The script must be editted to define the correct path to the file that lists
the packages to not be updated - see line 28.
"""

import os
from optparse import OptionParser

def parse_options():
	"""
	Parse the command line options
	"""
	global options
	usage = "usage: %prog [options]"
	parser = OptionParser(usage=usage)
	parser.add_option("-d", "--dry-run",
                      action="store_true", dest="dry_run",
                      help="dry run mode.  Shows which pacakges would be updated.")

	(options, args) = parser.parse_args()


def update_fink():
	no_update_file_name = '/Users/kwh/temp/fink_no_update.txt'
	no_update_list = open(no_update_file_name)
	no_update_items = no_update_list.readlines()

	listo = os.popen('fink list -o')

	update_list = []
	for line in listo:
		items = line.split()
		update_list.append(items[1])

	print 'Out of date fink packages:'
	for item in update_list:
		print item,
	print '\n'

	print 'The list of items flagged as "do not update" is defined in',\
	  no_update_file_name, '\n'

	for n, item in enumerate(no_update_items):
		no_update_items[n] = no_update_items[n].strip()
	
	print 'The following items are flagged as "do not update":'
	for item in no_update_items:
		if item[0] != '#':
			print item,
	print '\n'

	for n, item in enumerate(update_list):
		if item in no_update_items:
			update_list.pop(n)

	if len(update_list) > 0:
		cmd = 'fink update '
		for item in update_list:
			cmd += ' ' + item

		if options.dry_run == True:
			print 'Dry run mode.  The fink command would be:\n', cmd
		else:
			print 'The fink command will be:'
			print cmd, '\n'
			result = raw_input('Execute the above command? [Y/n]')
			if result == 'Y' or result == 'y' or result == '':
				print 'Updating packages'
				os.system(cmd)
			else:
				return
	else:
		print 'No packages require updating'

if __name__ == "__main__":
	parse_options()
	update_fink()