#!/usr/bin/env python3
# zlib -- deflate compression using the Zlib header format
import getopt
import zlib
import sys

def usage():
    print("Usage: zlib [-d | -0..9] <file>")
    print("")
    print("  -d      Decompress (inflate) the given file")
    print("  -0..9   Set deflate level (default is 6)")
    print("")
    print("If <file> is not given, stdin will be used instead.")

def compress(inf, outf, level):
    z = zlib.compressobj(level)
    while True:
        buf = inf.read(16384)
        if buf:
            buf = z.compress(buf)
            outf.write(buf)
        else:
            buf = z.flush()
            outf.write(buf)
            break

def decompress(inf, outf, **kwargs):
    z = zlib.decompressobj()
    while True:
        buf = inf.read(16384)
        if buf:
            buf = z.decompress(buf)
            outf.write(buf)
        else:
            buf = z.flush()
            outf.write(buf)
            break

arg0 = sys.argv[0].split("/")[-1]

inpath = "/dev/stdin"
outpath = "/dev/stdout"
mode = compress
level = 6

if arg0 in ("dezlib", "unzlib"):
    mode = decompress

try:
    opts, args = getopt.getopt(sys.argv[1:], "dh0123456789")
except getopt.GetoptError:
    usage()
    exit(2)

for opt, optarg in opts:
    if opt == "-h":
        usage()
        exit()
    elif opt == "-d":
        mode = decompress
    elif opt[1] in "0123456789":
        level = int(opt[1])

if args:
    inpath = args[0]

with open(inpath, "rb") as inf:
    with open(outpath, "wb") as outf:
        mode(inf, outf, level=level)
