import sys
import os

def main():
    print("OEM meta package install script")

    # Detect BU and platform ID
    if os.path.exists("/usr/share/volatile/bu"):
        detect_bu = open("/usr/share/volatile/bu").read()
        detect_bu = detect_bu.upper()
        detect_bu = detect_bu.strip('\n')
        print("Detected BU: " + detect_bu)
    else:
        print("Error: can not detect BU")
        detect_bu = ""

    if os.path.exists("/usr/share/volatile/getID.sh"):
        detect_platform = os.popen("/usr/share/volatile/getID.sh").read()
        detect_platform = detect_platform.upper()
        detect_platform = detect_platform.strip('\n')
        print("Detected platform: " + detect_platform)
    else:
        print('Error: can not detect platform')
        detect_platform = ""


    # get detail information of all available packages
    print('Get information of all available packages')
    package_all = os.popen('apt-cache dumpavail').read()
    package_line = package_all.splitlines(True)
    package_line_len = len(package_line)


    install_cmd = "apt-get --yes --allow-downgrades --allow-remove-essential --allow-unauthenticated -o apt::install-recommends=true install "

    # find meta package and install it
    print('Finding platform meta package ...')
    package_line_count = 0
    while package_line_count < package_line_len:
        name = package_line[package_line_count][9:]

        package_line_count = package_line_count + 1
        while package_line[package_line_count][0] != '\n':
            if package_line[package_line_count].find("Modaliases: oem-platform-meta(metainfo:bu" + detect_bu + "p" + detect_platform + ")") != -1:
                print('Found platform meta package: ' + name)
                print('Installing ...')
                os.system(install_cmd + name)
            package_line_count = package_line_count + 1

        package_line_count = package_line_count + 1


if __name__ == "__main__":
    main()
