#!python

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

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 = "yes"
        elif (sys.argv[2]) == "--create-archive=NO":
            archive = "no"
        else:
            print("Unknown argument.")
            help()
            exit()
    else:
        archive = "no"
    directory = sys.argv[1] + "/"

    def add(file):
        if ".deb" not in file:
            print(f"File {file} is not a .deb file - skipping.")
            return
        os.system('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("shasum -a 256 " + directory + file + " | cut -d \" \" -f 1").read(),
            "sha1": os.popen("shasum -a 1 " + directory + file + " | cut -d \" \" -f 1").read(),
            "md5": os.popen("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").read()
        output = control + filename + "\n" + md5 + sha1 + sha256 + filesize + "\n" + "\n"
        bundleid = control.partition('\n')[0].replace('Package: ', '')
        print("Adding entry:\n" + sha256 + md5 + sha1 + filesize + " (K)\nbundleID: " + bundleid)
        return output
    start_time = time.time()
    files = next(os.walk(directory))[2]
    with ThreadPoolExecutor(max_workers=len(files)) as executor:
        os.system("mkdir -p ./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("./Packages", "a")
                f.write(result)
                f.close()
                os.system('rm -rf ./tmp')
                wroteTo == "yes"
        if (archive) == "yes":
            if (wroteTo) == "yes":
                os.system("echo \"[DSP] BUILDING BZ2\"; bzip2 -5fkv ./Packages > ./Packages.bz2; echo \"[DSP] BUILDING XZ\"; xz -5fkev Packages > Packages.xz; echo \"[DSP] BUILDING LZMA\"; xz -5fkev --format=lzma Packages > Packages.lzma")
        print(f"Finished in {time.time() - start_time} seconds.")
        exit()
