#! /usr/bin/env python3

import os
import sys
import hashlib
import signal
import logging
import argparse

def process(target):
  prefix = ''
  if isinstance(target, str):
    log.info(f'opening {target!r}')
    stream = open(target, 'rb')
    prefix = f'{target}: '
  else:
    log.info('opening stdin in binary mode')
    stream = os.fdopen(target.fileno(), 'rb')

  hash = hashlib.md5()
  while True:
    log.info('reading a byte')
    c = stream.read(1)
    log.info(f'read {c!r}')
    if c:
      hash.update(c)
    else:
      break

  print(f'{prefix}{hash.hexdigest()}')

  stream.close()

parser = argparse.ArgumentParser(description=sys.argv[0])
parser.add_argument('files', metavar='file', nargs='*', help='Zero or more files to process')
parser.add_argument('-v', '--verbose', action='count', help='Enable debugging')
args = parser.parse_args()

logging.basicConfig(format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(msg)s')
log = logging.getLogger()
log.setLevel(logging.WARNING - (args.verbose or 0)*10)

signal.signal(signal.SIGPIPE, lambda signum, stack_frame: exit(0))

if args.files:
  for filename in args.files:
    process(filename)
else:
  if sys.stdin.isatty():
    parser.error('stdin is not redirected')
  process(sys.stdin)
