#!/usr/bin/env python3

import os, sys, shutil, jsonfig

__version__ = '0.1.0'

PTH={
	'build': './build',
	'src': '.',
	'lib': '{build}/usr/lib/python3/dist-packages',
	'bin': '{build}/usr/bin'
}

TEMPLATE="""{
	"comment": "See http://doc.somethingfunny.xyz/config/debbuild for more information.",
	"package": {
		"name": "cool-package",
		"version": "0.1.0",
		"arch": "all",
		"enhances": [
			"mid-package"
		],
		"suggests": [
			"my-other-cool-package"
		],
		"depends": [
			"python3"
		],
		"replaces": [
			"discontinued-package"
		],
		"install": {
			"{src}/main.py": "{bin}",
			"{src}/cool_lib": "{lib}"
		},
		"desc": "My cool package."
	},
	"author": {
		"name": "Cool Guy",
		"email": "someone@example.com"
	},
	"dirs": {
		"build": "./build",
		"src": "."
	}
}"""

#EXCEPTIONS
class ConfSecNotFound(Exception):...
class ConfValueNotFound(Exception):...

# Helper tools
class Rep:
	def __init__(self, reprlist={}):
		self.__reprlist = reprlist

	def __call__(self,*args,**kwargs):
		return self.replace(*args,**kwargs)

	def __getitem__(self,key):
		return self.__reprlist[key]

	def __setitem__(self,key,val):
		self.__reprlist[key] = val

	def replace(self,value):
		for key, val in self.__reprlist.items():
			value = value.replace(key,val)
		return value

class path:
	def rmtree(path):
		print(f'Removing directory tree: "{path}"')
		shutil.rmtree(path)

	def mkdir(path):
		print(f'Making directory: "{path}"')
		os.mkdir(path)

	def makedirs(path):
		print(f'Making directory: "{path}"')
		os.makedirs(path)

	def copy(source,target):
		print(f'Copying "{source}" to "{target}"')
		shutil.copy(source,target)

	def recurse(directory):
		pathlist = []
		pathlist.append(directory)
		for subpath in os.listdir(directory):
			subpath=directory+'/'+subpath
			if os.path.isdir(subpath):
				path.recurse(subpath)
			else:
				pathlist.append(subpath)
		return pathlist

def main():
	global PTH, TEMPLATE

	# Default config
	config_path = './debbuild.json'
	pkg_out= './{name}_{version}_{arch}.deb'

	#ARGS
	current = None
	for arg in sys.argv[1:]:
		if current:
			if current == 'config':
				config_path = arg
				current = None
		else:
			if arg in ['-c','--config']:
				current = 'config'
			elif arg in ['--template']:
				print(TEMPLATE)
				exit(0)

	# Read config file.
	#READCONF
	print('Reading configuration file...')
	config_file = jsonfig.JSONFile(config_path,fail_on_nonexist=True)
	try:
		conf = config_file.load()
	except FileNotFoundError:
		print(f'Config file not found. ({config_path})')
		exit(1)

	# Parse config file.
	#PARSECONF
	try:
		# Make sure required sections exist
		for sec in ['package','author']:
			if not sec in conf.keys():
				raise ConfSecNotFound(sec)

		pkg=conf['package']
		auth=conf['author']

		# Make sure required values exist
		for key in ['name','version','arch','desc']:
			if not key in pkg.keys():
				raise ConfValueNotFound(key)
		for key in ['name']:
			if not key in auth.keys():
				raise ConfValueNotFound(key)

		pkg_name = pkg['name']
		pkg_version = pkg['version']
		pkg_arch = pkg['arch']
		pkg_install=pkg.get('install')
		pkg_depends=pkg.get('depends')
		pkg_predepends=pkg.get('predepends')
		pkg_recommends=pkg.get('reccomends')
		pkg_suggests=pkg.get('suggests')
		pkg_breaks=pkg.get('breaks')
		pkg_replaces=pkg.get('replaces')
		pkg_enhances=pkg.get('enhances')
		pkg_homepage=pkg.get('homepage')
		pkg_desc = pkg['desc']
		auth_name = auth['name']
		auth_email = auth.get('email')

		# Encorporate optional values
		if 'dirs' in conf.keys():
			for key, val in conf['dirs'].items():
				PTH[key] = rep(val)
		if 'out' in pkg.keys():
			pkg_out = pkg['out']
	except (ConfSecNotFound,ConfValueNotFound) as e:
		if type(e) == ConfSecNotFound:
			print(f'Failed to read config file. (missing section "{e}")')
		if type(e) == ConfValueNotFound:
			print(f'Failed to read config file. (missing value "{e}")')
		print('For an example config file, see --template.')
		exit(1)

	rep = Rep({
		'{name}': pkg_name,
		'{version}': pkg_version,
		'{arch}': pkg_arch
	})
	for key, val in PTH.items():
		rep['{'+key+'}'] = rep(val)

	# Make build directory
	if os.path.exists(PTH['build']):
		path.rmtree(PTH['build'])
	path.makedirs(PTH['build'])
	path.makedirs(f'{PTH['build']}/DEBIAN')

	# Make control file
	control_path=f'{PTH['build']}/DEBIAN/control'
	print(f'Writing control file to "{control_path}"')
	with open(control_path,'w') as f:
		f.write(
			f"""Package: {pkg_name}
Version: {pkg_version}
Maintainer: {auth_name} <{auth_email}>
Architecture: {pkg_arch}
Built-Using: debbuild_{__version__}_all\n"""
		)
		if pkg_depends:
			f.write(f'Depends: {', '.join(pkg_depends)}\n')
		if pkg_predepends:
			f.write(f'Pre-Depends: {', '.join(pkg_predepends)}\n')
		if pkg_recommends:
			f.write(f'Recommends: {', '.join(pkg_recommends)}\n')
		if pkg_suggests:
			f.write(f'Suggests: {', '.join(pkg_suggests)}\n')
		if pkg_breaks:
			f.write(f'Breaks: {', '.join(pkg_breaks)}\n')
		if pkg_replaces:
			f.write(f'Replaces: {', '.join(pkg_replaces)}\n')
		if pkg_enhances:
			f.write(f'Enhances: {', '.join(pkg_enhances)}\n')
		if pkg_homepage:
			f.write(f'Homepage: {pkg_homepage}\n')
		if pkg_desc:
			f.write(f'Description: {pkg_desc}\n')
	
	# Install scripts.
	for script in ['preinst','postinst','prerm','postrm']:
		if os.path.exists(script_path := f'{rep['{src}']}/{script}'):
			path.copy(script_path, f'{rep['{build}']}/DEBIAN/{script}')
	
	# Set permissions.
	for file_path in path.recurse(f'{rep['{build}']}/DEBIAN'):
		os.chmod(file_path,0o755)

	# Copy files.
	for key, val in pkg_install.items():
		key=rep(key)
		val=rep(val)
		if not os.path.exists(val_dir := os.path.dirname(val)):
			path.makedirs(val_dir)
		path.copy(key,val)

	# Package file.
	os.system(f'dpkg-deb --root-owner-group -b {PTH['build']} {rep(pkg_out)}')

if __name__ == '__main__':
	main()
