#!/usr/bin/env python3

import logging, logging.handlers
import hmac, hashlib, uuid
import time, sys
import argparse, getpass

log = logging.getLogger(__name__)

if __name__ == '__main__':
  logger = logging.getLogger()
  logger.setLevel(logging.INFO)
  formatter = logging.Formatter("%(message)s")
  consoleHandler = logging.StreamHandler(sys.stdout)
  consoleHandler.setFormatter(formatter)
  logger.addHandler(consoleHandler)

  parser = argparse.ArgumentParser(description='Dihedral HMAC Generator')
  parser.add_argument('-k', '--key', default='ClientKey', help='Client Key')
  parser.add_argument('-s', '--secret', default=None, help='Secret Key')
  parser.add_argument('-m', '--method', default='POST', help='HTTP Method')
  parser.add_argument('-p', '--path', default='/publish/v1/events', help='HTTP Path')
  parser.add_argument('-t', '--timestamp', default=None, help='Request Timestamp')
  parser.add_argument('-n', '--nonce', default=None, help='The nonce value for the request')
  parser.add_argument('-H', '--header', action="store_true", help='Return just the header string for curl scripting')

  args = parser.parse_args()

  if not args.nonce:
    args.nonce = str(uuid.uuid4())
  if not args.timestamp:
    args.timestamp = "%d" % time.time()
  if not args.secret:
    args.secret = getpass.getpass('-> Enter your SecretKey: ')

  if not args.header:
    log.info(parser.description)
    log.info("-- HMAC Parameters ------------------------------------")
    log.info("Method:    %s", args.method)
    log.info("Path:      %s", args.path)
    log.info("Timestamp: %s", args.timestamp)
    log.info("Nonce:     %s", args.nonce)
    log.info("Secret:    %s ... %s", args.secret[0:1], args.secret[len(args.secret)-4:])

  stringToSign = "%s\n%s\n%s\n%s\n" % (args.method, args.path, args.timestamp, args.nonce)
  signature = hmac.new(bytes(args.secret, 'UTF-8'), bytes(stringToSign, 'UTF-8'), hashlib.sha256).hexdigest()

  if not args.header:
    log.info("-------------------------------------------------------")
    log.info('HMAC: %s', signature)
    log.info("-------------------------------------------------------")

  log.info('Authorization: hmac ck=%s,ts=%s,n=%s,sig=%s',
      args.key, args.timestamp, args.nonce, signature)

  if not args.header:
    log.info("-------------------------------------------------------")
