import os
import logging
import subprocess


if "USER" in os.environ:
    DEFAULT_GENCFG_HOME = "/home/{}/GENERILKA/".format(os.environ["USER"])
else:
    DEFAULT_GENCFG_HOME = "/tmp/GENERILKA"


def execute_gencfg_script(script, generilka_path=DEFAULT_GENCFG_HOME, fail_on_error=True):

    logging.info("Executing gencfg script # {}".format(script))
    executor = subprocess.Popen(
        script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    if fail_on_error:
        assert executor.wait() == 0, "Error while executing script {} in gencfg environment {}\n{}".format(script, generilka_path, "\n".join(executor.stderr.readlines()))

    result = executor.stdout.readlines()
    return result


class GencfgSVNApi(object):

    def __init__(self, generilka_path=None, do_update=False, skip_check=False):

        if generilka_path:
            self._generilka_path = generilka_path
        else:
            self._generilka_path = DEFAULT_GENCFG_HOME

        if not os.path.exists(self._generilka_path):
            os.makedirs(self._generilka_path)

        # TBD : fix code duplication, expose useful things to check_gencfg_ok and bootstrap_gencfg functions
        try:
            if not skip_check:
                execute_gencfg_script("./gen.sh run_checks", self._generilka_path, fail_on_error=True)
            else:
                assert execute_gencfg_script("ls gen.sh")
                assert execute_gencfg_script("ls db")
            if do_update:
                execute_gencfg_script('./update.sh')
        except:
            os.system("svn co svn+ssh://arcadia.yandex.ru/arc/trunk/arcadia/gencfg {}".format(self._generilka_path))
            execute_gencfg_script("./install.sh", self._generilka_path, fail_on_error=True)
            execute_gencfg_script("./utils/common/precalc_caches.py", self._generilka_path, fail_on_error=True)

            assert execute_gencfg_script("./gen.sh run_checks", self._generilka_path, fail_on_error=True), "Could not install gencfg into {}".format(self._generilka_path)

    def get_gencfg_home(self):
        return self._generilka_path

    def execute_gencfg_script(self, script, fail_on_error=True):
        return execute_gencfg_script(script, self._generilka_path, fail_on_error)


def main():
    pass

if __name__ == '__main__':
    main()
