#!/usr/bin/python
from __future__ import print_function

import os
import subprocess
import sys

from automation_tools import get_branchname, run_pylint, get_output, directory

from hooksettings import generates_pylint_report, updates_git_pages

if __name__ == '__main__':

    branchname = get_branchname()

    if branchname in generates_pylint_report:
        run_pylint(['./lint.py', '--score'])

    # Only reindent if there are no unstaged files
    numChanged = len(get_output(['git', 'diff', '--name-only']).splitlines())
    if numChanged == 0:
        # Reindent
        try:
            subprocess.call(['reindent', '-r', '-n', 'pygsti', 'test'])
            # Check if anything changed during our reindent
            numChanged = len(get_output(['git', 'diff', '--name-only']).splitlines())
            if numChanged > 0:
                subprocess.call(['git', 'add', '-u'])
                subprocess.call(['git', 'commit', '--no-verify', '--amend', '--no-edit'])
                print('Reindentation finished, commit amended')
        except Exception as e:
            print(e)
            print('Is reindent installed alongside python?\n' +
                  'On ubuntu/debian, try: apt-get install python-examples')
    else:
        print('Some files are still unstaged, automatic reindent (whitespace fix) aborted')

    with open(os.devnull, 'w') as FNULL:
        with directory('test'):
            print('Generating pylint report in background process. Checkout test/output/ in about a minute')
            subprocess.Popen(['./lint.py', '--score'], stdout=FNULL, stderr=FNULL) # Generate score, hope it doesn't hang

    if branchname in updates_git_pages:
        print('Updating github pages!')
        subprocess.call(['bash', '.git/hooks/create_git_html'])
        subprocess.call(['git', 'checkout', 'gh-pages'])
        os.system('cp temp_html/*.html tutorials/')
        subprocess.call(['git', 'add', 'tutorials/*.html'])
        subprocess.call(['git', 'commit', '--no-verify', '-m', '"Updates html in tutorials"'])

        if 'PUSHKEY' in os.environ and 'USER' in os.environ:
            USER     = os.environ['USER']
            PUSHKEY  = os.environ['PUSHKEY']
            push_uri = 'https://%s:%s@github.com/pyGSTio/pyGSTi.git' % (USER, PUSHKEY) # yikes
            try:
                print('Pushing. If this fails, there shouldn\'t be any useful output, since it would contain my access token')
                with open(os.devnull, 'w') as FNULL:
                    result = subprocess.call(['git', 'push', '--no-verify', push_uri, 'gh-pages'], stdout=FNULL, stderr=FNULL)
                    if result != 0:
                        print('Secure push failed')
                    else:
                        print('Secure push worked')
            except:
                print('Secure push failed')
        else:
            subprocess.call(['git', 'push']) # Will prompt user

        os.system('rm -rf temp_html') # yikes!
        subprocess.call(['git', 'checkout', branchname])

    sys.exit(0)
