#!/usr/bin/python3

import argparse
import datetime
import sqlite3
import time
import subprocess
from pathlib import Path
import os
import json

####################
pwr_config = {
    'queue': {
        'g01': 640,
        'g02': 160,
        'g21': 480,
        'c01': 100
    },
    'host': {
        'node2': 100,
    }
}
####################

hhist_pw_save = 'power suspended on policy'
hhist_pw_up = 'power resumed'

workdir = '/opt/skyformai/work/'
if 'CB_SHAREDIR' in os.environ:
    workdir = os.environ['CB_SHAREDIR']

PWDB = '%s/power.db' % workdir
PWTABLE = 'power_hist'

hq = {}
hosts = []
start_time = -1
end_time = -1
hacct = {}
pwacct = {}
debug = False
long = False

def db_init():  
    conn = sqlite3.connect(PWDB)
    conn.row_factory = sqlite3.Row    
    sql = 'SELECT * FROM %s' % PWTABLE
    c = conn.execute(sql)
    for r in c.fetchall():
        row = dict(r)
        hq[row['host']] = row['queue']
    conn.close()

def exec_cmd(cmd):
    if debug:
        print(cmd)
    sp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = sp.communicate()
    if out:
        if debug:
            print(out.decode("utf-8"))
        return out.decode("utf-8")
    if err:
        if debug:
            print(err.decode("utf-8"))
        return err.decode("utf-8")
    return sp.returncode 

def parse_hhist_output(out, year):
    for line in out.splitlines():
        if len(line) == 0:
            continue
        if hhist_pw_save not in line and hhist_pw_up not in line:
            continue
        host = line[line.index('<')+1:line.index('>')]
        if host not in hq:
            continue
        action = line[line.index('>')+1:line.index('by')].strip()
        timestamp = line[:line.rindex(':')]
        timestamp = '%s %s'%(year, timestamp)
        timestamp = datetime.datetime.strptime(timestamp, '%Y %a %b %d %H:%M:%S')
        timestamp = int(time.mktime(timestamp.timetuple()))
        if host not in hacct:
            hacct[host] = []   
        hacct[host].append({'action': action, 'time': timestamp})

parser = argparse.ArgumentParser(description='Power save statistics report',
                                 usage='pwacct [--all] [--start start_date] [--end end_date] [--long] [--debug]')
parser.add_argument('--start', help='Start date in ISO format - YYYY-MM-DD')
parser.add_argument('--end', help='End date in ISO format - YYYY-MM-DD')
parser.add_argument('--all', action='store_true', help='All power save statistics')
parser.add_argument('--long', action='store_true', help='Output in long format')
parser.add_argument('--debug', action='store_true', help='Print debug log')
args, _ = parser.parse_known_args()

db_init() 

debug = args.debug   
long = args.long
if args.all == True:
    start_time = 0
    end_time = int(time.time())
elif args.start != None or args.end != None:    
    if args.start != None:
        stime=datetime.datetime.strptime(args.start, '%Y-%m-%d').date()
        start_time = int(time.mktime(stime.timetuple()))
    if args.end != None:
        etime=datetime.datetime.strptime(args.end, '%Y-%m-%d').date()
        end_time = int(time.mktime(etime.timetuple()))
    if start_time == -1:
        start_time = 0
    if end_time == -1:
        end_time = int(time.time())     
else:
    end_time = int(time.time())     

if start_time != -1:
    pathlist = list(Path('%s/data' % workdir).rglob('cb.data.*'))
    pathlist.sort(key=lambda x: os.path.getmtime(x))
    for path in pathlist:
        file_time = int(str(path).split('.')[2])
        if file_time >= start_time and file_time <= end_time:
            out = exec_cmd(['/opt/skyformai/bin/csadmin', 'hhist', '-f', str(path)])
            parse_hhist_output(out, datetime.datetime.fromtimestamp(file_time).year)
out = exec_cmd(['/opt/skyformai/bin/csadmin', 'hhist'])
parse_hhist_output(out, datetime.datetime.now().year)            

pwacct = {}
pwacct['save_hours'] = 0
pwacct['save_pw'] = 0
pwacct['num_hosts'] = 0
if long:
    pwacct['hosts'] = []

for h, acct in hacct.items():
    num = len(acct)
    index = 0
    hsave = 0
    last_action = None
    for item in acct:
        action = item['action']
        atime = item['time']
        if debug:
            print('======')
            print('index=%d time=%d start_time=%s end_time=%s last_action=%s action=%s'%
                  (index, atime, start_time, end_time, action, last_action))
        if index == 0 and action == hhist_pw_up:
            if start_time > 0:
                hsave += atime - start_time
                last_action = action
        elif index == num-1 and action == hhist_pw_save:
            if end_time > atime:
                if last_action == None or last_action != action:
                    hsave += end_time - atime
                else:
                    hsave += end_time  
        elif action == hhist_pw_save:
             if last_action == None or last_action != action:
                hsave -= atime
                last_action = action
        elif action == hhist_pw_up:   
             if last_action == None or last_action != action:
                hsave += atime
                last_action = action
        if debug:        
            print('hsave=%d'%hsave)        
        index += 1
    hsave_sta = {}
    hsave_sta['host'] = h
    hsave_sta['power'] = 0
    if 'host' in pwr_config and h in pwr_config['host']:
        hsave_sta['power'] = pwr_config['host'][h]
    elif hq[h] in pwr_config['queue']:
        hsave_sta['power'] = pwr_config['queue'][hq[h]]
    hsave_sta['save_hours'] = round(hsave/3600, 2)
    hsave_sta['save_pw'] = round(hsave_sta['save_hours'] * hsave_sta['power'], 2)
    if long:
        pwacct['hosts'].append(hsave_sta)    
    pwacct['save_hours'] += hsave_sta['save_hours']
    pwacct['save_pw'] += hsave_sta['save_pw']
    pwacct['num_hosts'] += 1

print(json.dumps(pwacct, indent=4))
