#!/usr/bin/env python3

import birchenv
import os
import os.path
import shutil
import subprocess
import sys

# Genographer 1.6 requires that a genograph.cfg
# be in the directory in which it is launched.
# Curse you Microsoft, for inflicting this idiotic
# mindset on the whole world! 

#------------------------------------
# We need to get around the
# requirement that genograph.cfg must be present in every directory
# in which genographer will be run. The solution is to create a lock file
# for every instance of genographer. When a genographer job terminates,
# the lock file is removed. If no more lock files remain,
# genographer removes genograph.cfg.

LOCK = "genographer.lock." + os.getpid()
h_LOCK = open(LOCK, "w")
print("This file is created when an instance of genographer is running.", file=h_LOCK)
print("It should automatically be removed when genographer terminates. ", file=h_LOCK)

if not os.path.exists("genograph.cfg"):
    shutil.copyfile(os.path.join(birchenv.BIRCH, "java", "genographer", "genograph.cfg"), os.path.join(os.getcwd(), "genograph.cfg"))

command = ["java", "-cp", os.path.join(birchenv.BIRCH, "java", "genographer"), "genographer", \
    os.path.join(birchenv.BIRCH, "java", "genographer")]
command[6:] = sys.argv
subprocess.call(command)

os.remove(LOCK)

COUNT = 0
for file in os.listdir(os.getcwd()):
    if file.startswith("genographer.lock"):
        COUNT += 1

if COUNT == 0:
    os.remove("genograph.cfg")
