#!/usr/bin/env python
import argparse
import sys
import json

import pycriu

def handle_cmdline_opts():
	desc = 'CRiu Image Tool'
	parser = argparse.ArgumentParser(description=desc, formatter_class=argparse.RawTextHelpFormatter)
	parser.add_argument('command',
			    choices = ['decode', 'encode'],
			help = 'decode/encode - convert criu image from/to binary type to/from json')
	parser.add_argument('-i',
			    '--in',
			help = 'input file (stdin by default)')
	parser.add_argument('-o',
			    '--out',
			help = 'output file (stdout by default)')
	parser.add_argument('-f',
			    '--format',
			    choices = ['raw', 'nice', 'hex'],
			    nargs = '+',
			    default = [],
			help = 'raw  - all in one line\n'\
			       'nice - add indents and newlines to look nice(default for stdout)\n'\
			       'hex  - print int fields as hex strings where suitable(could be combined with others)')

	opts = vars(parser.parse_args())

	return opts

def inf(opts):
	if opts['in']:
		return open(opts['in'], 'r')
	else:
		return sys.stdin

def outf(opts):
	if opts['out']:
		return open(opts['out'], 'w+')
	else:
		return sys.stdout


def decode(opts):
	indent = None
	img = pycriu.images.load(inf(opts), opts['format'])

	# For stdout --format nice is set by default.
	if 'nice' in opts['format'] or ('raw' not in opts['format'] and opts['out'] == None):
		indent = 4

	f = outf(opts)
	json.dump(img, f, indent=indent)
	if f == sys.stdout:
		f.write("\n")

def encode(opts):
	img = json.load(inf(opts))
	pycriu.images.dump(img, outf(opts))

def main():
	#Handle cmdline options
	opts = handle_cmdline_opts()

	cmds = {
		'decode' : decode,
		'encode' : encode
	}

	cmds[opts['command']](opts)

if __name__ == '__main__':
	main()
