#!/bin/env python

import sys
from subprocess import call
import os
from cmdsignature.program import ProgramSignatureParser
from cmdsignature.interpreter import CmdSignatureInterpreter

def getScriptDir(file = __file__):
	return os.path.dirname(os.path.realpath(file))

if __name__ == "__main__":
	# no command
	if len(sys.argv) < 2:
		cmd = "docker run -t gofed/gofed:v1.0.0 /home/gofed/gofed/hack/gofed.sh -h"
	else:
		script_dir = getScriptDir(__file__)
		if script_dir.startswith("/usr/bin") or script_dir.startswith("/bin"):
			script_dir = "/usr/share/gofed"

		plugin_directory = "%s/cmd" % script_dir
		plugins = filter(lambda l: l.endswith(".yml"), os.listdir(plugin_directory))
		plugins = map(lambda l: "%s/%s" % (plugin_directory, l), plugins)

		parser = ProgramSignatureParser(
			"gofed",
			script_dir
		).parse(
			plugins,
			sys.argv[1:]
		)

		flags = parser.getCommandFlags(sys.argv[1])

		interpreter = CmdSignatureInterpreter(
			map(lambda l: "%s/cmd/%s" % (script_dir, l), flags),
			command = sys.argv[1],
			task = "gofed",
			image = parser.getCommandImage(sys.argv[1]),
			binary = "/home/gofed/gofed/hack/gofed.sh",
			keep_default_flags = True
		)

		interpreter.interpret(sys.argv[2:])

		cmd = interpreter.dockerSignature()

	exit(call(cmd, shell=True))
