# start-container.py
# Launcher of BEMS docker container
#

import os
import sys
import json
import subprocess
import argparse

INIT_SCRIPT = "run-container.sh"
INIT_PUB_SCRIPT = "run-container-pub.sh"

if __name__ == "__main__":
   parser = argparse.ArgumentParser(
      description="Launcher of BEMS docker container"
   )
   parser.add_argument("--conffile", required=True, type=str)
   args = parser.parse_args()

   print("Parsing configuration file : " + args.conffile)
   # Open and read the JSON file
   with open(args.conffile, 'r') as file:
      data = json.load(file)

   repotype = data['repository']['type']
   server = data['repository']['server']
   user = data['repository']['user']

   image = data['image']['name']
   tag = data['image']['tag']

   container = data['container']['name']
   folder = data['container']['folder']
   hasPub = data['container']['hasPub']
   heapSize = data['container']['heapSize']
   maxLogSize = data['container']['maxLogSize']
   maxLogFiles = data['container']['maxLogFiles']
   stopTimeout = data['container']['stopTimeout']

   # Debug
   print(f'Container : {container}')
   print(f'Folder : {folder}')
   print(f'Image : {user}/{image}:{tag}')
   print(f'Container has pub : {hasPub}')
   print(f'Container stop timeout : {stopTimeout}')

   currpath = os.path.dirname(os.path.abspath(__file__))
   
   if (hasPub == True):
      initScript = currpath + "/" + INIT_PUB_SCRIPT
   else:
      initScript = currpath + "/" + INIT_SCRIPT

   print("Launching init script: " + initScript)

   if (repotype == 'aws'):
      result = subprocess.call(f'{initScript} {container} {folder} {server} {image} {tag} {heapSize} {maxLogSize} {maxLogFiles} {stopTimeout}', shell=True)
   else:
      result = subprocess.call(f'{initScript} {container} {folder} {user} {image} {tag} {heapSize} {maxLogSize} {maxLogFiles} {stopTimeout}', shell=True)

   sys.exit(result)
