#!/usr/bin/env python


import os, sys
from treep import files
from treep import list_git_repos


def run(branch, commit):

    path = os.getcwd()
    workspace = path + os.sep + "workspace"

    if not os.path.isdir(workspace):
        print(
            "\nfailed to find a 'workspace' subdirectory in current directory\n"
        )
        return

    statuses = list_git_repos.get_statuses(workspace)

    return files.generate_yaml_configuration_files(
        path, statuses, "PROJECT", branch=branch, commit=commit
    )


def print_usage():

    print(
        "\n",
        "A 'workspace' folder is expected in the current directory.\n",
        "treep_to_yaml will create the treep configuration files corresponding\n",
        "to the repositories found in the workspace subfolders. The configuration\n",
        "will define only one project ('PROJECT'), consisting of all the repos.\n",
        "usage: treep_to_yaml mode\n",
        "\twith mode:\n",
        "\t\tsimple: generate config file without branch or commit information\n",
        "\t\tbranch: generate config file with branch name information\n",
        "\t\tcommit: generate config file with current commit hash information\n",
        "to use the generated files: copy them in a treep_<something> folder\n",
    )


def get_config(args):

    if len(args) != 2:
        print_usage()
        return None, None

    if args[1] not in ["simple", "branch", "commit"]:
        print_usage()
        return None, None

    if args[1] == "branch":
        return True, False

    if args[1] == "commit":
        return False, True

    return False, False


if __name__ == "__main__":

    branch, commit = get_config(sys.argv)

    if branch is not None:
        files = run(branch, commit)
        if files is not None:
            print("\ngenerated files:")
            for f in files:
                print("\t" + f)
            print("\n")
