#! /bin/python3
# -*- coding: utf-8 -*-
#
# This file is part of INGInious. See the LICENSE and the COPYRIGHTS files for
# more information about the licensing of this file.
import argparse
import sys

from inginious_container_api import run_student

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description='Runs a command in a secure environment.\n\
This command will proxy stdin, stdout, stderr, most signals and the return value. \n\n\
There are special return values: \n\
* 252 means that the command was killed due to an out-of-memory \n\
* 253 means that the command timed out \n\
* 254 means that an error occured while running the proxy')
parser.add_argument('--container', help="Name of the container to use. The default is the same as the current container", default=None)
parser.add_argument('--time', help="Timeout (in CPU time) for the container. The default is the same as the current container", type=int, default=0)
parser.add_argument('--hard-time', help="Hard timeout for the container (in real time). The default is three times the value indicated for --time",
                    type=int, default=0)
parser.add_argument('--memory', help="Maximum memory for the container, in Mo. The default is the same as the current container", type=int, default=0)
parser.add_argument('--share-network', help="Share the network stack of the grading container with the student container. This is not the case by "
                                            "default. If the container container has network access, this will also be the case for the student!",
                    action='store_true', dest='share_network')
parser.add_argument('--run-as-root', help="Tries to run the command in the student container with root access. This feature is in beta and should not be used yet", action='store_true')
parser.add_argument('--teardown-script', help="Specify, using string format, the commands to run when the student leaves the ssh connection, just before killing the student container. Example: \"python3 teardown_script.py\"", type=str, default="")

parser.add_argument('cmd', help="Command to be run on the remote container", nargs=argparse.REMAINDER)
args = parser.parse_args()

exit(run_student.run_student(cmd=' '.join(args.cmd), container=args.container, time_limit=args.time,
                             hard_time_limit=args.hard_time, memory_limit=args.memory,
                             share_network=args.share_network,
                             stdin=sys.stdin.fileno(), stdout=sys.stdout.fileno(), stderr=sys.stderr.fileno(),
                             signal_handler_callback=run_student._hack_signals, start_student_as_root=args.run_as_root, teardown_script=args.teardown_script))
