import os
import tarfile

with open("./package.toml", mode='r') as mani:
    data = mani.read()
    with open("./mock.pkg", mode='wb') as pkg:
        print("building header...")
        pkg.write(bytes([0x01, (len(data) >> 8) & 0xFF, len(data) & 0xFF]))
        print("writing manifest into pkg...")
        pkg.write(data.encode("utf-8"))
        with tarfile.TarFile("/tmp/pkgtar", 'w') as pkgtar:
            for root, dirs, files in os.walk("."):
                for file in files:
                    print(f"\33[2Kadd: {file}", end="\r", flush=True)
                    pkgtar.add(os.path.join(root, file))
        with open("/tmp/pkgtar", 'rb') as pkgtar:
            print("appending pkgtar to pkg...")
            pkg.write(pkgtar.read())
        print("deleting /tmp/pkgtar...")
        os.unlink("/tmp/pkgtar")
        print("closing write stream")
        pkg.close()