#!/usr/bin/python
# encoding: utf-8

#Initial script to create build-bot
import sys,os,shutil,glob,argparse

revNo = 0

parser = argparse.ArgumentParser(description='Build packages for different distributions')
parser.add_argument('--buildpath', metavar=os.path.normpath(sys.path[0]), default = os.path.normpath(sys.path[0]) , help ='path, where all files for building will be stored ) [default: current directory]')
parser.add_argument('--distributions', metavar="lucid maverick natty sid", default = "lucid maverick natty sid" , help ='distributions for building [default: lucid maverick]')
parser.add_argument('--architectures', metavar="i386 amd64", default = "i386 amd64" , help ='architectures to building [default: i386 amd64]')
args = parser.parse_args()

defaultPath = args.buildpath
distributionsNames = args.distributions.split()
distributionsArch = args.architectures.split()

# Check, whether base files for building exist

for distrName in distributionsNames:
	for archName in distributionsArch:
		distr_plus_arch = distrName+'_'+archName
		if not(os.path.exists('/var/cache/pbuilder/'+distr_plus_arch+'.tgz')):
			os.system('sudo pbuilder --create --basetgz /var/cache/pbuilder/'+distr_plus_arch+'.tgz --aptcache /var/cache/pbuilder/aptcache_'+archName+'/ --distribution '+distrName+' --architecture '+archName+' --components "main universe" --debootstrapopts --variant=buildd')
		os.system('sudo pbuilder --update --basetgz /var/cache/pbuilder/'+distr_plus_arch+'.tgz')

#Update to the latest revision or checkout
if os.path.exists(defaultPath+'/cleanBzr'):
	print "CleanBZR folder exists"
	print "Updating to the latest bzr version"
	os.chdir(defaultPath+'/cleanBzr/yade')
	os.system('bzr up')
	revNo=os.popen("LC_ALL=C bzr revno 2>/dev/null").readlines()[0][:-1]
else: 
	os.mkdir(defaultPath+'/cleanBzr')
	print "CleanBZR created"
	print "Checking out the latest bzr version"
	os.chdir(defaultPath+'/cleanBzr/')
	os.system('bzr checkout lp:yade --lightweight')
	os.chdir('yade')
	revNo=os.popen("LC_ALL=C bzr revno 2>/dev/null").readlines()[0][:-1]

os.chdir(defaultPath)
VERSION = 'bzr'+str(revNo)

# Prepare .dsc files for pbuilder
for distrName in distributionsNames:
	if os.path.exists(distrName) and (os.path.isdir(distrName)):
		shutil.rmtree(distrName)
	os.mkdir(distrName)
	os.chdir(distrName)
	shutil.copytree('../cleanBzr/yade','yade')
	os.chdir('yade')
	os.system('scripts/debian-prep ' + distrName)
	os.chdir('..')
	os.system('dpkg-source -b -I yade-'+VERSION)
	dscFile = glob.glob('*.dsc')[0]
	for archName in distributionsArch:
		os.mkdir(archName)
		os.system('sudo pbuilder --build --basetgz /var/cache/pbuilder/'+distr_plus_arch+'.tgz  --buildresult '+defaultPath+'/'+distrName+'/'+archName+' '+dscFile)
	os.chdir('..')


