#name = Updater
#version = 0.3.0
#hex = 8E489858A1

from http import server
import os
import platform
import urllib.request
import time
import sys
from wsgiref.simple_server import server_version
from zipfile import ZipFile
import hashlib

Program_atrib = []
os_name = platform.system()
os_version = platform.release()
os_architecture = platform.architecture()[0]

os.system('mode con lines=25 cols=100')
os.system('color E')
os.system('title SuK Program Updater')
def cls():
    os.system("cls")
def wait(msg):
    print(msg)
    os.system("pause > nul")
def download(name):
    root_path = os.path.dirname(name)
    name_index = 0
    ver_index = 0
    hex_index = 0
    index = 0
    #Check (Download)
    Program_atrib.clear()
    temp=[]
    update=[]
    local_version=[]
    server_version=[]
    try:
        with open(name,"r") as file:
            for line in file:
                temp.append(line.strip())
        del temp[3:]
    except:
        print("Critical Error: Path doesnt lead to valid Program!!\n\nUpdate was aborted do to Error\n\n")
        return None
    for e in temp:
        e = e.lower()
        Program_atrib.append(e.split(" ",3))
    
    for e in Program_atrib:
        if(e[0] == "#name"):
            name_index = index
        elif(e[0] == "#version"):
            ver_index = index
        elif(e[0] == "#hex"):
            hex_index = index
        else:
            print("Invalid Metadata!\n\nUpdate was aborted do to Error\n\n")
            return None
        index = index + 1
    
    try:
        #urllib.request.urlretrieve("https://file.steck-und-kot.de/."+ Program_atrib[name_index][2] + "/update.id","update.id")
        for line in urllib.request.urlopen("https://file.steck-und-kot.de/."+ Program_atrib[name_index][2] + "/update.id"):
            line = line.decode('utf-8')
            line = line.lower()
            line = line.replace("\n","")
            line = line.replace("\r","")
            update.append(line.split(" ",2))
    except:
        print("Error occured while fetching Update Identification File!\n\n\n")
        return None
    
    temp.clear()
    #with open("update.id","r") as file:
        #for line in file:
            #temp.append(line.strip())

    #for e in temp:
        #e = e.lower()
        #update.append(e.split(" ",3))

    temp.clear()
    
    temp.append((Program_atrib[ver_index][2].split(".",3)))
    
    for i in range(len(temp[0])):
        local_version.append(int(temp[0][i]))

    

    #Check Override Message
    if(update[0][0] == "#override"):
        cls()
        print("Update Identification File included an Override Command:")
        print(update[0][2]+"\n")
        print("Update can't proceed!\n\n\n")
        return None
    
    temp.clear()
    temp.append((update[1][2].split(".",3)))
    
    for i in range(len(temp[0])):
        server_version.append(int(temp[0][i]))
    #Check
    if(update[0][2] != Program_atrib[name_index][2]):
        print("Program name does not match with Update identification file!")
        cmd = input("Proceed anyway [y/(n)]?")
        if(cmd.lower() == "y"):
            pass
        else:
            print("\nUpdate aborted due to User Input\n\n")
            return None
    #Check Hex
    if(Program_atrib[hex_index][2] != update[2][2]):
        print("Critical Error: Hexadecimal Control number mismatch!\n\nUpdate was aborted due to Error\n\n")
        return None
    #Check Version
    if(local_version[0] < server_version[0]):
        pass
    elif(local_version[0] == server_version[0]):
        if(local_version[1] < server_version[1]):
            pass
        elif(local_version[1] == server_version[1]):
            if(local_version[2] < server_version[2]):
                pass
            else:
                print("Local Version newer than Server Version\nLocal Version: "+str(Program_atrib[ver_index][2])+"\nServer Version: "+str(update[1][2]))
                cmd = input("Download Update anyway [y/(n)]?")
                if (cmd.lower() == "y"):
                    pass
                else:
                    print("\nUpdate aborted due to User Input\n\n")
                    return None
        else:
            print("Local Version newer than Server Version\nLocal Version: "+str(Program_atrib[ver_index][2])+"\nServer Version: "+str(update[1][2]))
            cmd = input("Download Update anyway [y/(n)]?")
            if (cmd.lower() == "y"):
                pass
            else:
                print("\nUpdate aborted due to User Input\n\n")
                return None
    else:
        print("Local Version newer than Server Version\nLocal Version: "+str(Program_atrib[ver_index][2])+"\nServer Version: "+str(update[1][2]))
        cmd = input("Download Update anyway [y/(n)]?")
        if (cmd.lower() == "y"):
            pass
        else:
            print("\nUpdate aborted due to User Input\n\n")
            return None
    if(update[3][2] != os_name.lower()) or (update[4][2] != os_version.lower()) or (update[5][2] != os_architecture.lower()):
        print("Your System Specifications do not match match Update Identifications File")
        print("Your System:\nOperation System: "+os_name+"\nVersion: "+os_version+"\nArchitecture: "+os_architecture+"\n\n")
        print("Update Identification File:\nOperating System: "+update[3][2]+"\nVersion: "+update[4][2]+"\nArchitecture: "+update[5][2]+"\n\n")
        print("Updates might not work as expected!")
        cmd = input("Download Update anyway [y/(n)]?")
        if(cmd.lower() == "y"):
            pass
        else:
            print("Update aborted due to User Input\n\n\n")
            return None
    cls()
    #Downloading Updates
    print("Downloading Update...")
    try:
        urllib.request.urlretrieve("https://file.steck-und-kot.de/."+ Program_atrib[name_index][2] + "/" + update[6][2],update[6][2])      
    except:
        print("Error while Downloading Updates\n\n\n")
        os.system('del ' + update[6][2])
        return None
    #Extracting Archives
    print("Extracting Updates...")
    try:
        with ZipFile(update[6][2],"r") as arc:
            arc.extractall()
        os.system("xcopy /e /y" + " build\\*" + " " + root_path)
    except:
        print("Error while Extracting Updates\n\n\n")
        os.system("del " + update[6][2])
        os.system("rmdir /s /q build")
    
    
    print("Cleaning up...")
    
    os.system("del " + update[6][2])
    os.system("rmdir /s /q build")
        
    print("Update sucessfull")      
    wait("Press any key to return to menu...")
    return None
            
    pass
def update_updater():
    download("updater.py")
def about():
    cls()
    print("[About SuK Program Updater]".center(99))
    print("\n")
    print("Version: 0.3.0".center(99))
    print("Alpha Series \"Crystal Series\"".center(99))
    sysabt = "Running on " + platform.system() + " " + platform.release() + " " + platform.architecture()[0] + "\n"
    print(sysabt.center(99))
    print("(C) 2026, Steck und Kot".center(99))
    wait("\n\nPress any key to return...")
    cls()

print("Verifying Checksum with server...")
time.sleep(0.3)
#Check wether or not the updater is too old (e.g when new methods are introduced in newer versions, the .updater_minver on the Server gets updated.
try:
    updater_ver = []
    updater_minver = []
    temp = []
    readable_hash = ""
    
    with open("updater.py","rb") as f:
        bytes = f.read()
        readable_hash = hashlib.sha256(bytes).hexdigest();
    with open("updater.py","r") as f:
        for line in f:
            temp.append(line.strip())

    del temp[2:]
    del temp[:1]
    
    temp[0] = temp[0].split(" ",3)

    server_hash = []
    for line in urllib.request.urlopen("https://file.steck-und-kot.de/.con/.updater_hash"):
        line = line.decode('utf-8')
        line = line.lower()
        line = line.replace("\n","")
        line = line.replace("\r","")
        server_hash.append(line.split(" ",2))
   
    
    hash_available = 0
        
    for e in server_hash:
        if(temp[0][2] == e[0]):
            if(readable_hash == e[1]):
                hash_available = 1
            else:
                print("CHECKSUM MISMATCH: Updater can not verify correct Version! Please redownload the Program Updater!")
                wait("Press any key to quit...")
                sys.exit(1)
        else:
            pass
    if hash_available == 0:
        print("No Checksum for your Version of Program Updater was found on the Update Server! Please update your Program Updater\nIf your Version is up to date, consult Customer Support")
        wait("Press any key to quit...")
        sys.exit(1)
    print("Verifying Version with server...")
    temp[0] = temp[0][2].split(".",3)
    for e in temp[0]:
        updater_ver.append(int(e))
    temp.clear()
    for line in urllib.request.urlopen("https://file.steck-und-kot.de/.con/.updater_minimum"):
        line = line.decode('utf-8')
        line = line.lower()
        line = line.replace("\n","")
        line = line.replace("\r","")
        temp.append(line.split(" ",3))

    
   
    temp[0] = temp[0][2].split(".",3)
    for e in temp[0]:
        updater_minver.append(int(e))

    if(updater_ver[0] == updater_minver[0]):
        if(updater_ver[1] == updater_minver[1]):
            if(updater_ver[2] == updater_minver[2] or updater_ver[2] > updater_minver[2]):
               pass
            else:
                print("Your version of SuK Program Updater is no longer supported! Please Update the Program Updater")
                wait("Press any key to quit...")
                sys.exit(1)
        elif(updater_ver[1] > updater_minver[1]):
            pass
        else:
            print("Your version of SuK Program Updater is no longer supported! Please Update the Program Updater")
            wait("Press any key to quit...")
            sys.exit(1)
    elif(updater_ver[0] > updater_minver[0]):
        pass
    else:
        print("Your version of SuK Program Updater is no longer supported! Please Update the Program Updater")
        wait("Press any key to quit...")
        quit()
    
except SystemExit as e:
    if e.code == 1:
        raise       
except:
    print("Critical Error: Could not check minimum Version of the Updater! Check Internet Connection")
    wait()

print("Version verified! Starting Program Updater...")

time.sleep(0.25)
cls()
    
running = 1
while(running == 1):
    
    
    print("SuK Program Updater".center(99))
    print("Version 0.3\n".center(99))
    print("[1] Update Program".center(99))
    print("[2] Update Updater".center(99))
    print("[3] About Updater".center(99))
    print("[4] Quit\n".center(99))

    cmd = input("Type Selection and press enter>")

    if(cmd == ""):
        pass
    elif(int(cmd) == 1):
        cls()
        name = input("Enter Programm Path>")
        if(os.path.isfile(name) == False):
            print("Invalid Filename!\n\n\n")
        else:
            download(name)
    elif(int(cmd) == 2):
        update_updater()
    elif(int(cmd) == 3):
        about()
    elif(int(cmd) == 4):
        sys.exit()
    else:
        print("Invalid Selection!\n\n\n")





