import argparse
from subprocess import call
from os import remove

war_file = "./CVE-2017-9791.war"

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--flag", dest="flag", help="Flag to Use")
parser.add_argument("-p", "--port", dest="port", help="External Facing Port to Use")
parser.add_argument("-a", "--additional", dest="additional_file", help="Additional File to Include")
args = parser.parse_args()

flag = args.flag
port = args.port
additional_file = args.additional_file

if flag is None:
    print("please specify a flag with -f")
    exit(1)

if port is None:
    print("please specify an external port with -p")
    exit(1)

if additional_file is None:
    print("Please note you may add an additional file to the container using '-a ./filename.txt'")

flagfile = """
{0}
""".format(flag)

dockerfile = """FROM tomcat:alpine
COPY {0} /usr/local/tomcat/webapps/showcase.war
COPY ./flag.txt /usr/local/tomcat/flag.txt""".format(war_file)

file = open('flag.txt', 'w+')
file.write(flag)
file.close()

if additional_file is not None:
    dockerfile = """FROM tomcat:alpine
COPY {0} /usr/local/tomcat/webapps/showcase.war
COPY flag.txt /usr/local/tomcat/flag.txt
COPY {1} /usr/local/tomcat/{1}""".format(war_file, additional_file)

file = open('dockerfile', "w+")
file.write(dockerfile)
file.close()

call(["docker", "build", "-t", "ctrl/ctf-cve-2017-9791", "."])
containername = "CTF-CVE-2017-9791"
call(["docker", "run", "-d", "--name", containername, "-p", "{0}:8080".format(port), "ctrl/ctf-cve-2017-9791"])

remove("flag.txt")
remove("dockerfile")
