#!/usr/bin/env python3

import argparse
import re
import sys

parser = argparse.ArgumentParser()
parser.add_argument("hex_bytes", metavar="HB", type=str, nargs="*", help="Hex byte")
parser.add_argument("-i", "--stdin", action="store_true", help="Get bytes from stdin")
parser.add_argument(
    "-b", "--stdin-binary", action="store_true", help="Specify that stdin is raw bytes"
)
parser.add_argument("-r", "--reverse", action="store_true", help="Reverse byte order")
parser.add_argument("-H", "--hex", action="store_true", help="Output a normalized hex string")
parser.add_argument(
    "-x", "--hex-prefix", action="store_true", help="Output bytes seperated by ' 0x'"
)
parser.add_argument("-s", "--string", action="store_true", help="print escaped string literal")
parser.add_argument("-B", "--output-binary", action="store_true", help="print binary")
args = parser.parse_args()

if not args.stdin_binary:
    if not args.stdin:
        hex_bytes_str = "".join([hbs.removeprefix("0x") for hbs in args.hex_bytes])
    else:
        hex_bytes_str = "".join([hbs.removeprefix("0x") for hbs in sys.stdin.read().split()])

    buf = bytes.fromhex("".join([hbs.removeprefix("0x") for hbs in hex_bytes_str]))
else:
    buf = sys.stdin.buffer.read()

if args.reverse:
    buf = buf[::-1]
if args.string:
    print(repr(buf)[1:])
if args.output_binary:
    sys.stdout.buffer.write(buf)
elif not (args.hex or args.hex_prefix):
    sys.stdout.buffer.write(buf)
elif args.hex_prefix:
    print(" ".join([f"{b:#04x}" for b in buf]))
else:
    print(buf.hex())
