#!/usr/bin/python
# encoding: utf-8
import sys,os.path,re,shutil,time
DISTRIBUTION=sys.argv[1] if len(sys.argv)>1 else 'unstable'


if os.path.exists('RELEASE'):
	VERSION=file('RELEASE').readline().strip()
	UPDATE=(file('UPDATE').readline().strip() if os.path.exists('UPDATE') else '')
	print 'UPDATE is %s'%UPDATE
	SNAPSHOT=''
	PRIORITY = 0
	if ((re.sub('[^0-9.]','',VERSION))==''):
		PRIORITY = 200
	else:
		PRIORITY=int(10000*float(re.sub('[^0-9.]','',VERSION)))
		if re.match('^.*beta',VERSION): PRIORITY-=100
		if re.match('^.*rc[0-9]$',VERSION): PRIORITY-=100
		if UPDATE: PRIORITY+=int(re.sub('[^0-9]','',UPDATE))
elif os.path.exists('.bzr'):
	VERSION='bzr'+os.popen("LC_ALL=C bzr revno 2>/dev/null").readlines()[0][:-1]
	SNAPSHOT='-snapshot'
	PRIORITY=int(re.sub('[^0-9]','',VERSION))
	UPDATE=''
else:
	raise RuntimeError('Revision could not be determined (RELEASE or .bzr)')
print 'version %s%s%s, priority %d'%(VERSION,SNAPSHOT,('%s%s'%(VERSION,UPDATE) if UPDATE else ''),PRIORITY)
open('VERSION','w').write(VERSION+'\n')
_VERSION='-'+VERSION #used in templates


# rename a current folder and create orig.tar.gz
curName = os.path.basename(os.path.abspath(''))
newName = 'yade-%s' % (VERSION)
os.rename (('../'+curName), '../'+newName)
shutil.rmtree('.bzr')
os.system(('tar -czf ../yade-%s_%s.orig.tar.gz ../'+os.path.basename(os.path.abspath(''))+'/')%(VERSION,VERSION))
shutil.copytree('scripts/debian','./debian')


# control files
def copyReplace(f1,f2):
	"Copy file f1 to f2, evaluating all occurences of @...@ with eval(); they should expand to a string and can contain arbitrary python expressions."
	ff2=open(f2,'w')
	for l in open(f1):
		ff2.write(re.sub(r'@([^@]*)@',lambda m: str(eval(m.group(1))),l))
for f1,f2 in [
	('yade.postinst-template','yade-%s.postinst'%VERSION),
	('yade.desktop-template','yade-%s.desktop'%VERSION),
	('yade.docs-template','yade-%s.docs'%VERSION),
	('yade.examples-template','yade-%s.examples'%VERSION),
	('yade.install-template','yade-%s.install'%VERSION),
	('yade.menu-template','yade-%s.menu'%VERSION),
	('yade-doc.doc-base-template','yade-%s-doc.doc-base'%VERSION),
	('yade-doc.docs-template','yade-%s-doc.docs'%VERSION),
	('control-template','control')]:
		copyReplace('debian/'+f1,'debian/'+f2)
os.system('cp debian/yade16x16.xpm debian/yade-%s_16x16.xpm'%VERSION)
os.system('cp debian/yade32x32.xpm debian/yade-%s_32x32.xpm'%VERSION)


# package is yade-0.50, but with UPDATE .1, it is version 0.50.1

# write debian/changelog
try:
	open('debian/changelog','w').write(
	'''yade-%s (%s-1) %s; urgency=low

  * Automatic debian changelog entry for yade-%s

 -- %s <%s>  %s
'''%(VERSION,VERSION,DISTRIBUTION,VERSION,os.environ['DEBFULLNAME'],os.environ['DEBEMAIL'],time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime())))
except KeyError:
	print "Please, set DEBEMAIL and DEBFULLNAME as described here http://www.debian.org/doc/maint-guide/ch-first.en.html"

# remove some generated files
for p in ('doc/doxygen','doc/sphinx/_build','tags'):
	if not os.path.exists(p): continue
	if os.path.isdir(p): shutil.rmtree(p)
	else: os.remove(p)
