#!/usr/bin/env python

configuration_location = "%(configuration_location)s"
process_pid_file = "%(process_pid_file)s"

import sys
import os
import ConfigParser
import json
import subprocess

def loadConfig(config_file):
  config = ConfigParser.ConfigParser()
  config.read(config_file)
  return config

def main():
  config = loadConfig(configuration_location)
  script_path = config.get("service", "script-path")
  executable_folder = os.path.dirname(script_path)
  executable = os.path.basename(script_path)
  parameter_json = os.path.join(os.path.abspath(os.path.dirname(__file__)),
                                'parameters_%%s.json' %% executable)
  with open(parameter_json, 'w') as fjson:
    fjson.write(json.dumps(dict(config.items("parameter"))))

  process = subprocess.Popen(
    [script_path, parameter_json],
    stdin=None,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
  )
  with open(process_pid_file, "w") as pidfile:
    pidfile.write(str(process.pid))

if __name__ == "__main__":
  sys.exit(main())