#!/usr/bin/env python
# Copyright (C) 2015 Jurriaan Bremer.

import os.path
import sys

import hd


if __name__ == '__main__':
    if len(sys.argv) == 1:
        print 'Usage: %s <file> [options..]' % os.path.basename(sys.argv[0])
        exit(1)

    path = None
    args = {}

    # Get the terminal size in order to calculate the size that fits best.
    cols, _ = hd.get_terminal_size()

    for arg in sys.argv[1:]:
        if '=' not in arg:
            if path:
                print 'Please do not pass multiple files..'
                exit(1)
            path = arg
            continue

        key, value = arg.split('=', 1)
        args[key.strip()] = value.strip()

    if 'count' not in args and 'c' not in args:
        # Bytes required per combination of blocksize character.
        bytes_required = {1: 4, 2: 5, 4: 9}

        # Fetch the blocksize, if given.
        blocksize = int(args.get('blocksize', args.get('bs', 1)))

        # Each line has up to 12 columns used as overhead, so subtract those,
        # and adjust the size to an 8-byte alignment.
        args['count'] = ((cols - 12) / bytes_required[blocksize]) & ~7

    try:
        hd.hexdump(open(path, 'rb'), **args)
    except IOError:
        pass
