#!/usr/bin/env python

import argparse
import os

from logzero import logger
from sh import chmod

from ansible_dev_tools.config import ANSIBLE_DEV_TOOLS_WORKDIR
from ansible_dev_tools.config import ANSIBLE_DEV_TOOLS_WORKDIR_LOCKFILE
from ansible_dev_tools.config import ANSIBLE_DEV_TOOLS_WORKDIR_CURRENT


#########################################
#   INVENTORY 
#########################################

INVENTORY_INI = '''
el6host
el7host
el8host
'''

#########################################
#   INVENTORY SCRIPT
#########################################

INVENTORY_SCRIPT = '''
#!/usr/bin/env python

import json
import sys
from pprint import pprint

INV = {}
INV['_meta'] = {'hostvars': {}}

groups = ['one', 'two', 'three']
hosts = ['foo', 'bar', 'baz']

for idx, group in enumerate(groups):
    INV[group] = {}
    INV[group]['children'] = []
    INV[group]['vars'] = {}
    INV[group]['hosts'] = [hosts[idx]]

for host in hosts:
    INV['_meta']['hostvars'][host] = {}
    INV['_meta']['hostvars'][host]['ansible_connection'] = 'local'

print json.dumps(INV, indent=2)
'''

#########################################
#   LARGE INVENTORY SCRIPT
#########################################

INVENTORY_SCALE_SCRIPT = '''
#!/usr/bin/env python

import json
import os
import sys
import uuid
from pprint import pprint

MAXHOSTS = os.environ.get('MAXHOSTS') or 10
if not isinstance(MAXHOSTS, int):
    MAXHOSTS = int(MAXHOSTS)

MAXITEMS = os.environ.get('MAXITEMS') or 10
if not isinstance(MAXITEMS, int):
    MAXITEMS = int(MAXITEMS)

INV = {}
INV['_meta'] = {'hostvars': {}}

groups = ['all']
hosts = ['x' + str(x) for x in range(0, MAXHOSTS)]

for idx, group in enumerate(groups):
    INV[group] = {}
    INV[group]['children'] = []
    INV[group]['vars'] = {}
    INV[group]['hosts'] = [x for x in hosts]

    for host in hosts:
        INV['_meta']['hostvars'][host] = {}
        INV['_meta']['hostvars'][host]['ansible_connection'] = 'local'
        INV['_meta']['hostvars'][host]['ansible_ssh_host'] = 'el7host'
        INV['_meta']['hostvars'][host]['ansible_ssh_user'] = 'root'
        INV['_meta']['hostvars'][host]['ansible_ssh_private_key_file'] = '~/.ssh/id_TEST'

        items = [str(x) for x in range(0, MAXITEMS)]
        items = ['/opt/test/%s' % host + x for x in items]
        items = [x + '/' + str(uuid.uuid4()) for x in items]
        INV['_meta']['hostvars'][host]['TESTLIST'] = items

print(json.dumps(INV, indent=2))
'''

#########################################
#   CONFIG
#########################################

ANSIBLE_CFG = '''
[defaults]
host_key_checking = False
'''


#########################################
#   PLAYBOOK 
#########################################

PLAYBOOK = '''
- hosts: el8host
  connection: local
  gather_facts: False
  tasks:
    - shell: whoami
'''

#########################################
#   TEST SCRIPT
#########################################

TESTSH = '''
#!/bin/bash
export SSH_AUTH_SOCK=0
VERSION=$(ansible --version | head -n1 | awk '{print $2}')
ansible-playbook -vvvv -i inventory site.yml
RC=$?
exit $RC
'''
#chmod +x test.sh

#########################################
#   REPORT SCRIPT
#########################################

REPORTSH = '''
#!/bin/bash

# | Tables        | Are           | Cool  |
# | ------------- |:-------------:| -----:|
# | col 3 is      | right-aligned | $1600 |
# | col 2 is      | centered      |   $12 |
# | zebra stripes | are neat      |    $1 |

# nostate.log
# withstate.log

VERSIONS=\$(ansible-list-versions)

echo "version | rc"
echo "------ | ------"
for VERSION in \$VERSIONS; do
    #echo "## \$VERSION"
    STATERC=\$(fgrep "\$VERSION ;" returncodes.txt | tail -n1 | cut -d\; -f2)
    echo "\$VERSION | \$STATERC"
done
'''


def create_workdir(repo, number, refresh=False):

    FILEMAP = [
        ['ansible.cfg', ANSIBLE_CFG, False],
        ['inventory', INVENTORY_INI, False],
        ['inventory_script.py', INVENTORY_SCRIPT, True],
        ['inventory_scale.py', INVENTORY_SCALE_SCRIPT, True],
        ['site.yml', PLAYBOOK, False],
        ['test.sh', TESTSH, True],
        ['report.sh', REPORTSH, True]
    ]

    workdir = os.path.join(ANSIBLE_DEV_TOOLS_WORKDIR, repo + '-' + str(number))
    if not os.path.exists(workdir) or refresh:
        if not os.path.exists(workdir):
            os.makedirs(workdir)
        for fm in FILEMAP:
            fn = os.path.join(workdir, fm[0])
            if not os.path.exists(fn) or refresh:
                logger.info('write %s' % fn)
                with open(fn, 'w') as f:
                    f.write(fm[1])
                if fm[2]:
                    logger.info('chmod +x %s' % fn)
                    chmod('+x', fn)

    with open(ANSIBLE_DEV_TOOLS_WORKDIR_LOCKFILE, 'w') as f:
        f.write(workdir + '\n')

    return workdir


def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--repo', default='ansible', choices=['ansible'], help="which repo the issue is from")
    parser.add_argument('--number', help="which issue number you are working on")
    parser.add_argument('--refresh', action='store_true', help="rewrite all the helper files")
    parser.add_argument('--current', action='store_true', help="show the current/last workdir")
    args = parser.parse_args()

    if args.current:
        print(ANSIBLE_DEV_TOOLS_WORKDIR_CURRENT)
    else:
        assert args.number
        workdir = create_workdir(args.repo, args.number, refresh=args.refresh)
        print(workdir)


if __name__ == "__main__":
    main()
