#!/usr/bin/env python3

import os, sys, shutil, jsonfig

__version__ = '0.1.3'

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}"
		},
		"permissions": {
			"{bin}/main.py": "755"
		},
		"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 pathtool:
	def exists(path):
		return os.path.exists(path)

	def islink(path):
		return os.path.islink(path)

	def isdir(path):
		return os.path.isdir(path)

	def chdir(path):
		os.chdir(path)

	def getcwd():
		return os.getcwd()

	def chmod(path, mode):
		print(f'Changing mode of "{path}" to {oct(mode)}')
		os.chmod(path,mode)

	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 listdir(path):
		return os.listdir(path)

	def copy(source,target):
		print(f'Copying "{source}" to "{target}"')
		if pathtool.isdir(source):
			shutil.copytree(source,target)
		else:
			shutil.copy(source,target)

	def recurse(path):
		data = {'files':[],'directories':[]}
		orig_dir = pathtool.getcwd()
		if not pathtool.isdir(path):
			data['files'].append(path)
			return data
		pathtool.chdir(path)

		remaining = ['.']
		data['directories']+=remaining

		while len(remaining) > 0:
			for rempath in remaining:
				try:
					ldir = pathtool.listdir(rempath)
				except:
					continue
				for subpath in ldir:
					full_path = f'{rempath}/{subpath}'.replace('//','/')

					if not pathtool.exists(full_path):
						continue
					if pathtool.islink(full_path):
						continue

					if pathtool.isdir(full_path):
						data['directories'].append(full_path)
						remaining.append(full_path)
					else:
						data['files'].append(full_path)
				remaining.remove(rempath)
		pathtool.chdir(orig_dir)
		return data

def main():
	global PTH, TEMPLATE

	rep = Rep()

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

	#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)
			elif arg in ['--clean']:
				clean=True

	# 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_permissions=pkg.get('permissions')
		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['{name}'] = pkg_name
	rep['{version}'] = pkg_version
	rep['{arch}'] = pkg_arch
	for key, val in PTH.items():
		rep['{'+key+'}'] = rep(val)

	# Make build directory
	if pathtool.exists(PTH['build']):
		pathtool.rmtree(PTH['build'])
	pathtool.makedirs(PTH['build'])
	pathtool.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 pathtool.exists(script_path := f'{rep['{src}']}/{script}'):
			pathtool.copy(script_path, f'{rep['{build}']}/DEBIAN/{script}')

	# Set permissions.
	result = pathtool.recurse(debpath := f'{rep['{build}']}/DEBIAN')
	for file_path in result['files']+result['directories']:
		pathtool.chmod(f'{debpath}/{file_path}',0o755)

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

	# Set package permissions.
	if pkg_permissions:
		for key, val in pkg_permissions.items():
			key=rep(key)
			if pathtool.isdir(key):
				for subpath in pathtool.recurse(key)['files']:
					pathtool.chmod(f'{key}/{subpath}', int(val,base=8))
			else:
				pathtool.chmod(key, int(val,base=8))

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

	# Cleanup.
	if clean:
		pathtool.rmtree(PTH['build'])

if __name__ == '__main__':
	main()
