import os;

BUILDNO_FILE = 'buildno.txt'

PKG_FILE_UDEB_TEMPLATE = 'podcatcher_udeb_template.pkg'
PKG_FILE_UDEB = 'podcatcher_udeb.pkg'
PKG_FILE_UREL_TEMPLATE = 'podcatcher_urel_template.pkg'
PKG_FILE_UREL = 'podcatcher_urel.pkg'
HEADER_FILE = '..\\inc\\buildno.h'
BUILDNO_TAG = 'BUILDNO'

def update_buildno(buildno_file):
	#read previous build number
	f = open(buildno_file, 'r')
	buildno = int(f.read())
	f.close()
	
	# increment build number and write it back to the file
	buildno = buildno + 1
	buildno_str = '%d' % buildno

	print 'New build number is %d' % buildno
	
	f = open(buildno_file, 'w')
	f.write(buildno_str)
	f.close()
	return buildno
	
def update_pkg(pkg_template, pkg_file, buildno):
	print 'Writing %s' % pkg_file
	#update 'build' number in PKG file
	f = open (pkg_template, 'r')
	g = open (pkg_file, 'w')
	
	buildno_str = '%d' % buildno

	for line in f:
		line = line.replace(BUILDNO_TAG, buildno_str)
		g.write(line)
		
def update_header(header_file, buildno):
	print 'Writing %s' % header_file
	buildno_str = '// Build number generated by increment_buildno.py, do not edit manually\r\n#define BUILD_NO %d' % buildno
	
	f = open(header_file, 'w')
	f.write(buildno_str)
	f.close()
	return buildno

new_buildno = update_buildno(BUILDNO_FILE)
update_pkg(PKG_FILE_UDEB_TEMPLATE, PKG_FILE_UDEB, new_buildno)
update_pkg(PKG_FILE_UREL_TEMPLATE, PKG_FILE_UREL, new_buildno)
update_header(HEADER_FILE, new_buildno)
print 'Remember to rebuild to get the build number into the about dialog!'