#!/usr/bin/env python3

import os

uarchdate = {
  'airmont':20150401, # XXX: not sure about exact date
  'broadwell':20141027,
  'core2':20060726,
  'goldmont':20160418,
  'haswell':20130604,
  'skylake':20150805,
  'tigerlake':20200902,
  'zen3':20201105,
}

uarchname = {
  'airmont':'Airmont',
  'broadwell':'Broadwell',
  'core2':'Core 2',
  'goldmont':'Goldmont',
  'haswell':'Haswell',
  'skylake':'Skylake',
  'tigerlake':'Tiger Lake',
  'zen3':'Zen 3',
}

def sortkey(m):
  uarch = ''.join(m.split('-')[:1])
  return uarchdate[uarch]

machines = sorted(os.listdir('benchmarks'),key=sortkey,reverse=True)

def lib25519(m):
  uarch = uarchname[''.join(m.split('-')[:1])]

  with open(f'benchmarks/{m}') as f:
    for line in f:
      line = line.split()
      if len(line) < 4: continue
      if line[:3] == ['dh_x25519_keypair','selected','32']:
        dh_keypair = int(line[3])
      if line[:3] == ['dh_x25519','selected','32']:
        dh = int(line[3])
      if line[:3] == ['sign_ed25519_keypair','selected','32']:
        sign_keypair = int(line[3])
      if line[:3] == ['sign_ed25519','selected','59']:
        sign = int(line[3])
      if line[:3] == ['sign_ed25519_open','selected','59']:
        verify = int(line[3])
      if line[:3] == ['nPbatch_montgomery25519','selected','16']:
        nPbatch_16 = int(line[3])
      if line[:3] == ['multiscalar_ed25519','selected','16']:
        multiscalar_16 = int(line[3])

  C = '<span class=lib25519>'
  D = '</span>'
  out.write(f'| | {C}lib25519{D} | {C}{dh_keypair}{D} | {C}{dh}{D} | {C}{nPbatch_16//16}{D} | {C}{sign_keypair}{D} | {C}{sign}{D} | {C}{verify}{D} | {C}{multiscalar_16//16}\n')

def openssl(m):
  uarch = uarchname[''.join(m.split('-')[:1])]

  with open(f'speedcomparison/openssl/{m}') as f:
    for line in f:
      line = line.split()
      if len(line) < 2: continue
      if line[:1] == ['x25519-keygen-main']:
        dh_keypair = int(line[1])
      if line[:1] == ['x25519-dh-main']:
        dh = int(line[1])
      if line[:1] == ['ed25519-keygen-main']:
        sign_keypair = int(line[1])
      if line[:1] == ['ed25519-sign-main']:
        sign = int(line[1])
      if line[:1] == ['ed25519-verify-main']:
        verify = int(line[1])

  C = '<span class=openssl>'
  D = '</span>'
  out.write(f'| {uarch} | {C}OpenSSL{D} | {C}{dh_keypair}{D} | {C}{dh}{D} | | {C}{sign_keypair}{D} | {C}{sign}{D} | {C}{verify}{D} | |\n')

with open('doc/speed.md','w') as out:
  with open('autogen/md-speed-top') as f:
    out.write(f.read())
  out.write('\n\n')
  out.write('| uarch | software | X key | X dh | X batch | Ed key | Ed sign | Ed verif | Ed MSM |\n')
  out.write('| :---- | :------- | ----: | ---: | ------: | -----: | ------: | -------: | -----: |\n')
  for m in machines:
    openssl(m)
    lib25519(m)
  out.write('\n\n')
  with open('autogen/md-speed-bot') as f:
    out.write(f.read())
