#!/usr/bin/env python
"""Commit .travis.yml file to the repos"""

from git import Repo
import os
import shutil

def main():
    """
    Where all the action happens.

    :return: None
    """

    github_org = '<GitHub org>'

    repos = {
        'repo-test': {
            'repo_type': 'module',
            'branches': [
                'master',
                '1.x'
            ]
        },
        'another-repo-test': {
            'repo_type': 'site',
            'branches': [
                '2.x',
                'feature-branch'
            ]
        }
    }

    travis_yml_repo = {
        'repo': 'travis-dist-files-repo',
        'branch': '1.x'
    }

    travis_status_image_token = '<token>'

    # Clone Travis repo.
    travis_yml_repo_path = '/tmp/{}'.format(travis_yml_repo['repo'])
    if os.path.exists(travis_yml_repo_path):
        shutil.rmtree(travis_yml_repo_path)

    print "[INFO] Cloning Travis repo {}".format(travis_yml_repo['repo'])
    Repo.clone_from('git@github.com:{org}/{repo}.git'.format(org=github_org, repo=travis_yml_repo['repo']), travis_yml_repo_path, branch=travis_yml_repo['branch'])

    print "[INFO] Starting process to commit .travis.yml file to the repos"
    for repo_name, repo_data in repos.iteritems():
        # Clone repo.
        print "[INFO] Cloning {}".format(repo_name)
        repo_path = '/tmp/{}'.format(repo_name)
        if os.path.exists(repo_path):
            shutil.rmtree(repo_path)

        try:
            Repo.clone_from('git@github.com:{org}/{repo}.git'.format(org=github_org, repo=repo_name), repo_path)
        except Exception, e:
            print "[ERROR] Unable to clone {repo}. {message}".format(repo=repo_name, message=str(e))

        repo = Repo(repo_path)
        git = repo.git

        for branch in repo_data['branches']:
            # Switch to the right branch.
            print "[INFO] Checking out branch {}".format(branch)

            try:
                git.checkout(branch)
            except Exception, e:
                print "[ERROR] Unable to checkout the branch {branch}. {message}".format(branch=branch, message=str(e))

            # Copy .travis.yml from the source to the repo.
            print "[INFO] Copying travis.{repo_type}.dist.yml to {repo_path}/.travis.yml".format(repo_type=repo_data['repo_type'], repo_path=repo_path)
            shutil.copyfile('{travis_source}/dist/travis.{repo_type}.dist.yml'.format(travis_source=travis_yml_repo_path, repo_type=repo_data['repo_type'], repo_path=repo_path), '{}/.travis.yml'.format(repo_path))

            # Append Travis status image to file.
            repo_readme = '{}/README.md'.format(repo_path)
            if os.path.isfile(repo_readme):
                if not 'Build Status' in open(repo_readme).read():
                    print "[INFO] Adding Travis status image to README.md"
                    travis_status_image = '[![Build Status](https://travis-ci.com/{org}/{repo}.svg?token={token}&branch={branch})](https://travis-ci.com/{org}/{repo})'.format(org=github_org, repo=repo_name, token=travis_status_image_token, branch=branch)
                    # Append the image markup.
                    with file(repo_readme, 'r') as original:
                        repo_readme_original = original.read()
                    with file(repo_readme, 'w') as modified:
                        modified.write("{}\n".format(travis_status_image) + repo_readme_original)

            # Commit and push the changes.
            print "[INFO] Committing and pushing the changes to {} branch".format(branch)
            git.add(".")

            try:
                git.commit("-m", "Added Travis integration")
                git.push('origin', branch)
            except Exception, e:
                print "[ERROR] Unable to commit and push to the branch {branch}. {message}".format(branch=branch, message=str(e))

        # Delete the repos.
        shutil.rmtree(repo_path)
        print "[INFO] Local repo {} has been deleted".format(repo_name)

    # Delete Travis repo.
    shutil.rmtree(travis_yml_repo_path)

if __name__ == "__main__":
    main()