#!/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import time
import logging
import subprocess


logging.basicConfig(level=logging.INFO, format='[%(asctime)s %(levelname)s] %(message)s')
logger = logging.getLogger('easyuc_test')


def get_homepath():
    fpath = os.path.abspath(__file__)
    for i in range(2):
        fpath = os.path.dirname(fpath)
        default_path = os.path.join(fpath, 'conf/default.ini')
        if os.path.exists(default_path):
            return fpath

    return ''


def exec_cmd(cmd, stdin=None):
    proc = subprocess.Popen(
        args=cmd,
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )

    out, _ = proc.communicate(stdin)
    return proc.returncode, out


def analyse(lines):
    logger.debug(lines)
    ret = {}
    for line in lines:
        if not line:
            continue
        if 'please check' in line:
            name = line.strip().split()[2]
            ret[name] = True

    logger.debug('analyse result: %s' % ret)
    return ret


def main(ip, password):
    count = 1000
    success = 0
    stat = {}
    cost_times = []

    homepath = get_homepath()
    if not homepath:
        logger.error('should run it with easyuc, exit 1')
        sys.exit(1)

    uninstall_input = 'YES'
    if ip == localhost:
        install_cmd = '%s/bin/easyuc -ip %s' % (homepath, ip)
    else:
        install_cmd = '%s/bin/easyuc -ip %s -p' % (homepath, ip)
        uninstall_input = '%s\nYES' % password

    uninstall_cmd = '%s -uninstall' % install_cmd

    start = time.time()
    for i in range(count):
        logger.info('install iter count: %s' % (i+1))
        st = time.time()
        code, output = exec_cmd(install_cmd, stdin=password)
        if code == 0:
            time_elapsed = round(time.time() - st, 2)
            cost_times.append(time_elapsed)
            success += 1
        else:
            lines = output.strip().split('\n')
            result = analyse(lines)
            for key in result.keys():
                if key in stat:
                    stat[key] += 1
                else:
                    stat[key] = 1

        code, output = exec_cmd(uninstall_cmd, stdin=uninstall_input)
        if code != 0:
            logger.error('uninstall FAILED')
            break

    end = time.time()
    stat_output = []
    stat_output.append('total time: %.2fs' % (end - start))
    stat_output.append('success/total: %s/%s (%.2f%%)' % (success, i+1, success * 1.0 / (i+1)))
    avg_time = 0
    if success:
        avg_time = sum(cost_times) / success
    stat_output.append('average time of successfully install: %.2fs' % avg_time)
    stat_output.append('FAILED app(s):')
    tmp = []
    for key, cnt in stat.iteritems():
        tmp.append((key, cnt))

    tmp.sort(key=lambda x: -x[1])
    for item in tmp:
        stat_output.append('\t%s\t%s' % (item[0], item[1]))

    stat_log = os.path.join(homepath, 'log/stat.log')
    with open(stat_log, 'a') as fp:
        fp.write('\n'.join(stat_output))
        fp.write('\n')

    print '\n'.join(stat_output)
    print


if __name__ == '__main__':
    from optparse import OptionParser
    localhost = '127.0.0.1'
    parser = OptionParser('test easyuc, installation in single machine')
    parser.add_option('--ip', help='target ip to install, default %s' % localhost, default=localhost)
    parser.add_option('--password', help='password of root in the target ip, in order to connect ssh')
    (args, _) = parser.parse_args()
    main(args.ip, args.password)
