#!/usr/bin/env python
import os
import sys
import yaml
import configurationvalues as confvals




def _choosebranch(branchlist):
    """ Print out the possible installation options for the user
        and return his choice
    """

    while True:
        print "Please choose a branch from the following list:"
        for index, b in enumerate(branchlist):
            print "  {0} - {1}".format(index, b)

        try:
            choice = int(raw_input("your choice: "))
            if choice >= 0 and choice < len(branchlist):
                return branchlist[choice]
        except ValueError:
            pass


def main(args):
    """ The job of this script is to create the branch config file in
    the meta/configurations directory.  That file has one key, and that key is
    "branch".  It allows the system to know which branch install we are
    working off of.
    """

    # Note: Because this tool is meant to be used on a clean install, that is,
    # one of the first things it does is set up which branch we are using, I
    # have to figure out the paths relative to where it is installed.

    # create the needed paths to the configuration files
    pbranch = os.path.join(
        confvals.getprojectpath(),
        confvals.getlayoutvalue('configuration\.branch'))

    # get the branch choice from the user
    branchlist = confvals.getconfigvalue('branch', isbranchdependent=False)
    branch = _choosebranch(branchlist)

    documentdict = dict()
    documentdict['branch'] = branch

    # write the branch configuration file with the correct value
    with file(pbranch, 'w') as stream:
        stream.write(yaml.dump(documentdict))


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
