#!/usr/bin/python3
import subprocess
from apt.cache import Cache
from math import ceil

def get_update_packages_list(allpacks):
    # update packages list
    clearlist = []
#    if allpacks == 1:
#        subprocess.run(["apt-get", "update"])
#    else:
#        subprocess.run(["apt-get", "update", "-o", "Dir::Etc::sourceparts='sources.list'"])
    aptproc = subprocess.run(["apt", "list", "--upgradable"], capture_output=True, text=True)
    if aptproc.returncode == 0:
        list = aptproc.stdout.split("\n")
        for package in list[1:]:
            if (not package.isspace()) and (len(package) != 0) & (package.find("/") > 0): #TODO test &
                clearlist.append(package[0:package.find('/')])
    return clearlist

def calc_installed_size(packlist: list):
    cache = Cache()
    size = 0
    for pack in packlist:
        size += cache[pack].candidate.installed_size / 1024
    return ceil(size / 1024)

def calc_size(packlist: list):
    cache = Cache()
    size = 0
    for pack in packlist:
        size += cache[pack].candidate.size / 1024
    return ceil(size / 1024)

def get_required_space_in_stdout(allpacks = 0):
    packages_list = get_update_packages_list(allpacks)
    size_to_install_Mb = 0
    if len(packages_list) != 0:
        size_to_install_Mb = calc_installed_size(packages_list)
        size_Mb = calc_size(packages_list)
        print(ceil( (size_Mb + size_to_install_Mb) / 1024) )  #DO NOT REMOVE it
        return 0
    else:
        return 1

exit(get_required_space_in_stdout())
