#!/usr/bin/python

from mixpanel import Mixpanel
import pdb

import argparse
import sys
import getpass
import socket
import subprocess
import os

from os.path import expanduser

parse = argparse.ArgumentParser(description='Send CORD logs to mixpanel.')
parse.add_argument('--corddir', dest='corddir', action='store',default=None, help='CORD Directory')
parse.add_argument('--event', dest='event', action='store',default=None, help='Event Name')
parse.add_argument('--finish', dest='finish', action='store_true',default=False, help='Finish')
parse.add_argument('--status', dest='status', action='store',default=None, help='Exit status')

args = parse.parse_args()

corddir = expanduser(args.corddir)
build_version_file = '/tmp/cord-build'
cord_version_file = '/tmp/cord-build-version'

try:
    mp = Mixpanel("7d5ca3b3ff870dbeda89c9d5af59e9e9")
    hostname = socket.gethostname()

    context = {}
    context['debian-version'] = open('/etc/debian_version').read().strip()

    os.chdir(corddir+'/orchestration/xos')
    p = subprocess.Popen(['git','rev-parse','HEAD'], stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)

    git_hash,err = p.communicate()
    
    context['last-commit'] = git_hash

    if (args.status):
        context['status'] = args.status

    config = open(corddir+'/build/config/cord_in_a_box.yml').read().splitlines()
    for l in config:
        if 'cord_profile:' in l:
            context['profile'] = l.rstrip().rsplit(' ')[-1].replace("'","")

    context['user'] = getpass.getuser()

    name = ''
    idx=0
    lst = hostname.split('.')
    lst.reverse()
    for i in lst:
        name='.'.join([name,i]).lstrip('.')

        context['level-%d'%idx] = name
        idx+=1

    if (args.finish):
        logfile = open(corddir+'/install.out').read().splitlines()
        snapshot = logfile[-20:]
        snapshot = filter(lambda x:x, snapshot)
        context['snapshot'] = snapshot

    try:
        build_id = open(build_version_file).read().rstrip()
    except:
        build_id = context['user'] + name

    # Figure out whether we're in master or what
    try:
    	cord_version = open(cord_version_file).read().rstrip()
    except:
	os.chdir(corddir)
	possible_versions = ['master','cord-1.0','cord-2.0']

	cord_version = 'personal'
	try:
	    for v in possible_versions:
		diff = os.popen('repo forall -c "git stash 2>/dev/null 1>/dev/null;git diff -b opencord/%s 2>/dev/null;git stash pop 2>/dev/null 1>/dev/null"'%v).read()
		if (not diff):
		    cord_version = v
		    break
	except:
	    pass
        
    open(cord_version_file,'w').write(cord_version)
    context['version'] = cord_version
    mp.track(build_id, args.event, context)
except Exception,e:
    print str(e)
    pass
