#!python

import time
import sys
import os
import bz2
import concurrent
from concurrent.futures.thread import ThreadPoolExecutor
info = "Copyright (c) Monotrix 2021- | Has no dependencies except for binutils for DEB extraction"

if __name__ == "__main__":
    def help():
        print("Usage: py-scanpackages ./debs --create-archive=YES")
    if len(sys.argv) == 1:
        help()
        exit()
    if len(sys.argv) == 3:
        if (sys.argv[2]) == "--create-archive=YES":
            archive = True
        elif (sys.argv[2]) == "--create-archive=NO":
            archive = False
        else:
            print("Unknown argument.")
            help()
            exit()
    else:
        archive = False
    directory = sys.argv[1] + "/"

    def add(file):
        if (file.endswith(".deb")):
            os.system(f"ar x {directory}{file}; mv ./control.tar.gz ./tmp; rm -rf data.tar.gz data.tar.lzma debian-binary; cd ./tmp; tar xvf ./control.tar.gz")
            sums = {
                "sha256": os.popen(f"shasum -a 256 {directory}/{file} | cut -d \" \" -f 1").read(),
                "sha1": os.popen(f"shasum -a 1 {directory}/{file} | cut -d \" \" -f 1").read(),
                "md5": os.popen(f"md5 {directory}/{file}  | cut -d \" \" -f 4").read(),
                "size": os.stat(directory + file).st_size
            }
            sha256 = "SHA256: " + str(sums["sha256"])
            sha1 = "SHA1: " + str(sums["sha1"])
            md5 = "MD5sum: " + str(sums["md5"])
            filesize = "Size: " + str(sums["size"])
            filename = "Filename: " + directory + file
            control = open("./tmp/control", "r")
            output = control.read() + filename + "\n" + md5 + sha1 + sha256 + filesize + "\n" + "\n"
            bundleid = control.read().partition("\n")[0].replace("Package: ", "")
            print(f"Adding entry:\n{sha256}{md5}{sha1}{filesize} (K)\nbundleID: {bundleid}")
            control.close()
            return output
        else:
            print(f"File {file} is not a .deb file - skipping.")
            return
    start_time = time.time()
    files = next(os.walk(directory))[2]
    with ThreadPoolExecutor(max_workers=50) as executor:
        os.mkdir(f"./tmp")
        futures = [executor.submit(add, file) for file in files]
        futures, _ = concurrent.futures.wait(futures)
        for future in futures:
            result = str(future.result())
            if (result != "None"):
                f = open(f"./Packages", "a")
                f.write(result)
                f.close()
                os.system(f"rm -rfv ./tmp")
        if archive:
            bz2contents = bz2.compress(open("Packages", "rb").read(), 5)
            bzout = open("Packages.bz2", "wb")
            bzout.write(bz2contents)
            bzout.close()
        print(f"Finished in {time.time() - start_time} seconds.")
        exit()
