"""GNUmed database pruning DML generator.

This script generates DML for pruning database tables
before restoring backups.

Theory of operation:

The script reads a plaintext format database backup of the
--data-only variety as generated by pg_dump and creates the
appropriate DML commands to prune the tables which are
inserted into by the backup.

It is useful to pre-process the dump with:

	cut -f -5 -d " " data-only-dump.sql | grep -E "^(SET)|(INSERT)"

to weed out superfluous cruft.
"""
#==================================================================
__author__ = "Karsten.Hilbert@gmx.net"
__license__ = "GPL v2 or later (details at https://www.gnu.org)"

import sys, os.path, logging


_log = logging.getLogger('gm.bootstrapper')

#==================================================================
def generate_pruning_dml(filename=None):

	# FIXME: encoding may need configuration
	backup_file = open(filename, mode = 'rt', encoding = 'utf8')
	backup_path, name = os.path.split(filename)
	name, ext = os.path.splitext(name)
	dml_name = os.path.join(backup_path, '%s-prune_tables.sql' % name)
	dml_file = open(dml_name, mode = 'wt', encoding = 'utf8')

	prev_table = None
	idx = 1

	for line in  backup_file:
		print(idx)
		idx += 1
		# reproduce configuration
		if line.startswith('SET '):
			dml_file.write(line)

		# detect tables to prune
		if line.startswith('INSERT INTO '):
			table = line.split()[2]
			# skip duplicates
			if prev_table == table:
				continue
			prev_table = table
			dml_file.write('delete from %s;\n' % table)

	dml_file.close()
	backup_file.close()

#==================================================================
# main
#------------------------------------------------------------------
if __name__ == "__main__" :

	generate_pruning_dml(sys.argv[1])
