#!/usr/bin/env python3
# auto-debuild - Automatic Generation of Debian Packages
# Copyright (C) 2012 Ralf Jung <post@ralfj.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

import os, shutil, stat, time, subprocess, sys, shlex, tempfile, argparse, multiprocessing
from collections import OrderedDict

# a dict with some useful additional getters which can convert types and handle one-element lists like their single member
class ConfigDict(dict):
	def getstr(self, name, default = None):
		if not name in self: return default
		val = self[name]
		if isinstance(val, list):
			if len(val) != 1: raise Exception('%s is a list, but it should not' % name)
			return val[0]
		else:
			return val
	
	def getint(self, name, default = None):
		return int(self.getstr(name, default))
	
	def getbool(self, name, default = None):
		val = self.getstr(name, default)
		if isinstance(val, bool): return val # already a bool
		return val.lower() in ('true', 'yes', 'on', '1')

# create a safe-to-call shell command from the array
def safeCall(*args):
	res = ""
	for arg in args:
		assert arg.find("'") < 0 # ' is not supported
		if len(res): res += " "
		res += "'"+arg+"'"
	return res

# Load a section-less config file: maps parameter names to space-separated lists of strings (with shell quotation)
# Lines starting with spaces are continuation lines
def loadConfigFile(file):
	# read config file
	linenr = 0
	with open(file) as file:
		result = ConfigDict()
		curKey = None
		for line in file:
			linenr += 1
			isCont = len(line) and line[0].isspace() # remember if we were a continuation line
			if isCont and curKey is None:
				raise Exception("Invalid config, line %d: Starting with continuation line" % linenr)
			line = line.strip()
			if not len(line) or line.startswith("#"): continue # skip empty and comment lines
			try:
				if isCont:
					# continuation line
					result[curKey] += shlex.split(line)
				else:
					# option line
					pos = line.index("=") # will raise exception when substring is not found
					curKey = line[:pos].strip()
					result[curKey] = shlex.split(line[pos+1:]) # shlex.split also strips
			except Exception:
				raise Exception("Invalid config, line %d: Error parsing line (quoting issue?)" % linenr)
	# add some convencience get functions
	return result

# representation of a build system
class BuildSystem:
	def __init__(self, ruleMaker, buildDepends = [], binaryDepends = []):
		self.ruleMaker = ruleMaker
		self.buildDepends = buildDepends
		self.binaryDepends = binaryDepends

# abstract representation of rules file
class RulesFile:
	def __init__(self):
		self.env = {}
		self.dh = []
		self.dhWith = set()
		self.rules = OrderedDict()
	
	def env2str(self):
		res = ""
		for name in self.env: # we rely on the name being sane (i.e., no special characters)
			val = self.env[name]
			assert val.find("'") < 0 # ' is not supported
			if len(res): res += " "
			res += name+"='"+val+"'"
		return res

	def write(self, f):
		print("#!/usr/bin/make -f", file=f)
		print(file=f)
		print("%:", file=f)
		# write proper dh call
		dh = self.dh
		if self.dhWith:
			dh.append('--with='+','.join(self.dhWith))
		print('\t'+self.env2str()+' dh $@ '+safeCall(*dh), file=f)
		# write remaining rules
		for rule in self.rules:
			print(file=f)
			print("override_dh_"+rule+":", file=f)
			for line in self.rules[rule]:
				print("\t"+line, file=f)

# rule-makers
def cmakeRules(r, config):
	buildDir = config.getstr('buildDir', 'build')
	srcDir = os.getcwd()
	r.dh += ["--buildsystem=cmake", "--builddirectory="+buildDir] # dh parameters
	r.rules['auto_configure'] = [
		safeCall("mkdir", "-p", buildDir),
		safeCall("cd", buildDir) + " && " +
		  safeCall("cmake", srcDir, "-DCMAKE_INSTALL_PREFIX=/usr", *config.get('cmakeParameters', []))
	]
	r.rules['auto_clean'] = [safeCall('rm', '-f', os.path.join(buildDir, 'CMakeCache.txt'))] # clean old cmake cache

def automakeRules(r, config):
	buildDir = config.getstr('buildDir', 'build')
	srcDir = os.getcwd()
	# "build" is what we are building *on*, and "host" is what we are building *for* (and GNU is weird...)
	# also, we don't really support cross-building... ;-) (to do so, we'd have to write shell code that checks whether BUILD_GNU_TYPE
	#  and HOST_GNU_TYPE are equal, and if they are not, add a --host parameter)
	r.dh += ["--buildsystem=autoconf", "--builddirectory="+config.getstr('buildDir')]
	r.rules['auto_configure'] = [
        (safeCall(*config['autogen']) + " && " if 'autogen' in config else '') +
		safeCall("mkdir", "-p", buildDir),
		safeCall("cd", buildDir) + " && " +
		'BUILD_TYPE=$$(dpkg-architecture -qDEB_BUILD_GNU_TYPE) && ' + # doing the expansion beforehand ensures that we cancel if it fails
		'MULTIARCH=$$(dpkg-architecture -qDEB_HOST_MULTIARCH) && '+
		safeCall(srcDir+"/configure") +
			' --build=$$BUILD_TYPE '+ # do the escape manually here so we can use the variables (there's no user-controlled string in here anyway)
			'--prefix=/usr --includedir=/usr/include --mandir=/usr/share/man --infodir=/usr/share/info '+
			'--libdir=/usr/lib/$$MULTIARCH --libexecdir=/usr/lib/$$MULTIARCH '+
			safeCall('--docdir=/usr/share/doc/'+config['binaryName'], '--sysconfdir=/etc', '--localstatedir=/var', *config.get('automakeParameters', []))
	]
	r.rules['auto_clean'] = [safeCall("rm", "-f", "--", buildDir+"/config.status")] # do not re-use old configuration

def makefileRules(r, config):
	r.dh += ["--buildsystem=makefile"]
	r.rules['auto_configure'] = []

def noneRules(r, config):
	r.dh += ["--buildsystem=makefile"] # makefile does the least possible harm
	r.rules['auto_configure'] = []
	r.rules['auto_build'] = []
	r.rules['auto_clean'] = []
	return r

# build systems
buildSystems = {
	'cmake': BuildSystem(cmakeRules, ["cmake"]),
	'automake': BuildSystem(automakeRules),
	'makefile': BuildSystem(makefileRules),
	'none': BuildSystem(noneRules),
}

# utility functions
def commandInBuildEnv(config, command):
	schroot = config.getstr('schroot')
	if schroot is not None: command = ['schroot', '-c', schroot, '--'] + command
	return command

def getArchitecture(config):
	cmd = commandInBuildEnv(config, ['dpkg-architecture', '-qDEB_HOST_ARCH'])
	output = subprocess.check_output(cmd)
	return output.decode('utf-8').strip('\n') # chop off the \n at the end

def writeDependency(f, name, list):
	if len(list):
		print(name+": "+', '.join(list), file=f)

# actual work functions
def deleteDebianFolder():
	if os.path.islink('debian'):
		target = os.readlink('debian')
		if os.path.exists(target):
			shutil.rmtree(target)
		os.remove('debian')
	elif os.path.exists('debian'):
		shutil.rmtree('debian')

def createDebianFiles(config):
	if not isinstance(config, ConfigDict):
		config = ConfigDict(config)
	sourceName = config.getstr('sourceName')
	binaryName = config.getstr('binaryName', sourceName+'-local')
	config['binaryName'] = binaryName # make it usable by build systems
	name = config.getstr('name', os.getenv('USER')) # os.getlogin() fails in minimal chroots
	email = config.getstr('email', os.getenv('USER')+'@'+os.uname()[1]) # user@hostname
	debDir = os.path.expanduser(config.getstr('debDir'))
	buildSystem = buildSystems[config.getstr('buildSystem')] # get the data immediately
	version = config.getstr('version') # version name excluding epoch (used for filenames)
	fullVersion = str(config.getint('epoch'))+':'+version if 'epoch' in config else version # version name including epoch
	parallelJobs = config.getint('parallelJobs', multiprocessing.cpu_count())
	packageArchitecture = config.getstr('architecture', 'any')
	withPython2 = config.getbool('withPython2', False)
	withSIP = config.getbool('withSIP', False)
	withAutoreconf = config.getbool('withAutoreconf', False)
	# add some build dependencies (a bit hacky adding it to the build system...)
	if withSIP:
		withPython2 = True
		buildSystem.buildDepends.append("python-sip")
		buildSystem.binaryDepends.append("${sip:Depends}")
	if withPython2:
		buildSystem.buildDepends.append("python")
		buildSystem.binaryDepends.append("${python:Depends}")
	if withAutoreconf:
		buildSystem.buildDepends.append("dh-autoreconf")
	# we return the list of files generated, so we need to know the architecture
	arch = getArchitecture(config)
	files = []
	# create folders
	if os.path.exists('debian') or os.path.islink('debian'): raise Exception('debian folder already exists?')
	if config.getbool('useTmp', True):
		tempdir = tempfile.mkdtemp(prefix='auto-debuild-')
		os.symlink(tempdir, 'debian')
	else:
		os.mkdir('debian')
	if not os.path.exists(debDir): os.makedirs(debDir)
	# source format file
	os.mkdir('debian/source')
	with open('debian/source/format', 'w') as f:
		print("3.0 (native)", file=f)
	# compat file
	with open('debian/compat', 'w') as f:
		print("9", file=f)
	# copyright file
	with open('debian/copyright', 'w') as f:
		print("Auto-generated by auto-debuild, not suited for distribution", file=f)
	# changelog file
	with open('debian/changelog', 'w') as f:
		print(sourceName,"("+fullVersion+")","UNRELEASED; urgency=low", file=f)
		print(file=f)
		print("  * Auto-generated by auto-debuild", file=f)
		print(file=f)
		print(" --",name,"<"+email+">  "+time.strftime('%a, %d %b %Y %H:%M:%S %z'), file=f)
	# control file
	with open('debian/control', 'w') as f:
		# source package
		print("Source:",sourceName, file=f)
		print("Section:",config.getstr('section', 'misc'), file=f)
		print("Priority: extra", file=f)
		print("Maintainer: %s <%s>" % (name, email), file=f)
		writeDependency(f, 'Build-Depends', ["debhelper (>= 9)"] + buildSystem.buildDepends + config.get('buildDepends', []))
		print("Standards-Version: 3.9.3", file=f)
		# main binary package
		print(file=f)
		print("Package:",binaryName, file=f)
		print("Architecture:",packageArchitecture, file=f)
		if 'binaryMultiArch' in config:
			print("Multi-Arch:",config.getstr('binaryMultiArch'), file=f)
		writeDependency(f, "Pre-Depends", ["${misc:Pre-Depends}"] + config.get('binaryPreDepends', []))
		writeDependency(f, "Depends", ["${shlibs:Depends}", "${misc:Depends}"] + buildSystem.binaryDepends +
			config.get('binaryDepends', []))
		writeDependency(f, "Recommends", config.get('binaryRecommends', []))
		writeDependency(f, "Provides", config.get('binaryProvides', [sourceName]))
		writeDependency(f, "Conflicts", config.get('binaryConflicts', []))
		writeDependency(f, "Breaks", config.get('binaryBreaks', []) + config.get('binaryBreaksReplaces', []))
		writeDependency(f, "Replaces", config.get('binaryReplaces', []) + config.get('binaryBreaksReplaces', []))
		print("Description:",sourceName,"(auto-debuild)", file=f)
		print(" Package auto-generated by auto-debuild.", file=f)
		files.append(os.path.join(debDir, "{}_{}_{}.deb".format(binaryName, version, arch)))
		files.append(os.path.join(debDir, "{}-dbgsym_{}_{}.deb".format(binaryName, version, arch)))
		# shim packages
		for shim in config.get('binaryShims', []):
			print(file=f)
			print("Package:",shim, file=f)
			print("Section:",config.getstr('section', 'misc'), file=f)
			print("Priority: extra", file=f)
			print("Architecture:",packageArchitecture, file=f)
			writeDependency(f, "Depends", ["${misc:Depends}", binaryName+" (= ${binary:Version})"])
			print("Description:",sourceName,"shim for",shim,"(auto-debuild)", file=f)
			print(" Package pretending to be "+shim+", auto-generated by auto-debuild.", file=f)
			files.append(os.path.join(debDir, "{}_{}_{}.deb".format(shim, version, arch)))
	# install file
	with open('debian/'+binaryName+'.install', 'w') as f:
		for line in config.get('binaryInstallFiles', []):
			if line.startswith('/'): # a file from within the package, not from the source tree
				line = 'debian/'+binaryName+line
			print(line, file=f)
	# maintainer scripts for alternatives
	if 'alternatives' in config:
		with open('debian/'+binaryName+'.postinst', 'w') as f:
			print("#!/bin/sh", file=f)
			print("set -e", file=f)
			print('if [ "$1" = "configure" ]; then', file=f)
			for alternative in config.get('alternatives'):
				alternative = shlex.split(alternative)
				print(safeCall('update-alternatives', '--install', alternative[0], alternative[1], alternative[2], alternative[3]), file=f)
			print('fi', file=f)
			print(file=f)
			print('#DEBHELPER#', file=f)
			print(file=f)
			print('exit 0', file=f)
		with open('debian/'+binaryName+'.prerm', 'w') as f:
			print("#!/bin/sh", file=f)
			print("set -e", file=f)
			print('if [ "$1" = "remove" ]; then', file=f)
			for alternative in config.get('alternatives'):
				alternative = shlex.split(alternative)
				print(safeCall('update-alternatives', '--remove', alternative[1], alternative[2]), file=f)
			print('fi', file=f)
			print(file=f)
			print('#DEBHELPER#', file=f)
			print(file=f)
			print('exit 0', file=f)
	# rules file: build system specific
	with open('debian/rules', 'w') as f:
		# pre-fill rule file with our global defaults
		r = RulesFile()
		r.rules['auto_test'] = []
		r.rules['auto_install'] = [safeCall('dh_auto_install', '--destdir=debian/'+binaryName)] # install everything into the binary package
		r.rules['auto_configure'] = ['dh_auto_configure'] # make sure there is an override (we may just append to it later)
		r.rules['usrlocal'] = [] # we *do* want to install things in /usr/local
		# patch rule file for build system: may only touch auto_* rules and the dh options
		buildSystem.ruleMaker(r, config)
		# global rules
		r.env["DEB_BUILD_OPTIONS"] = 'parallel='+str(parallelJobs)
		r.dh += ['--parallel']
		if withPython2:
			r.dhWith.add('python2')
			r.rules['python2'] = ['dh_python2 --no-guessing-versions --no-shebang-rewrite']
			if withSIP:
				r.rules['python2'].append(safeCall('dh_sip', '-p'+binaryName))
		if withAutoreconf:
			r.dhWith.add('autoreconf')
		r.rules['builddeb'] = [safeCall('dh_builddeb', "--destdir="+debDir)] # passing this gobally to dh results in weird problems (like stuff being installed there, and not in the package...)
		# installation rule
		if 'binarySkipFiles' in config:
			r.rules['auto_install'].append(safeCall('cd', 'debian/'+binaryName) + " && " + safeCall('rm', *config.get('binarySkipFiles')))
		# make the doc folder of the other packages a symlink (dbg, shims)
		r.rules['installdocs'] = [safeCall('dh_installdocs', '--link-doc='+binaryName)]
		# wait after configuration?
		if config.getbool('waitAfterConfig', False):
			r.rules['auto_configure'].append("@"+safeCall('read', '-p', 'Configuration done. Hit "Enter" to build the package. ', 'DUMMY_VAR')) # if we run in dash, we need to tell it which variable to use for the result...
		# dump it to a file
		r.write(f)
	mode = os.stat('debian/rules').st_mode
	os.chmod('debian/rules', mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
	# return list of files that will be created
	return files

def buildDebianPackage(config):
	if not isinstance(config, ConfigDict):
		config = ConfigDict(config)
	commands = ['dpkg-checkbuilddeps', 'debian/rules clean', 'debian/rules build', 'fakeroot debian/rules binary']
	command = ['bash', '-c', ' && '.join(commands)] # make it all one command, so we don't have to open and close the chroot too often
	subprocess.check_call(commandInBuildEnv(config, command))
	deleteDebianFolder() # cleanup: the debian folder only contains what we just created

###################################################################
# if we are called directly as script
if __name__ == "__main__":
	try:
		# read command-line arguments
		parser = argparse.ArgumentParser(description='Automatic Generation of Debian Packages')
		parser.add_argument("-w", "--wait-after-config",
							action="store_true", dest="wait_after_config",
							help="Wait for user confirmation after configuration is finished")
		args = parser.parse_args()
		# get config
		config = loadConfigFile('auto-debuild.conf')
		config['waitAfterConfig'] = args.wait_after_config
		# generate debian files
		if os.path.exists('debian') or os.path.islink('debian'):
			if input("A debian folder already exists, do you want to remove it and whatever it links to (y/N)? ").lower() != "y":
				sys.exit(1)
			deleteDebianFolder()
		files = createDebianFiles(config)
		# check if a file is overwritten
		overwritten_files = list(filter(lambda file: os.path.exists(file), files))
		if overwritten_files:
			if input("Do you want to overwrite {} (y/N)? ".format(', '.join(overwritten_files))).lower() != "y":
				sys.exit(1)
		# run compilation
		buildDebianPackage(config)
		# install files
		print("Installing created deb files...")
		subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
	except (subprocess.CalledProcessError, KeyboardInterrupt) as e: # for some exceptions, a stackrace is usually pointless
		print(file=sys.stderr)
		print(file=sys.stderr)
		if isinstance(e, KeyboardInterrupt): # str(e) would be the empty string
			print("Interruped by user", file=sys.stderr)
		else:
			print("Error during package creation: %s" % str(e), file=sys.stderr)
		print(file=sys.stderr)
		sys.exit(1)
