import time
import os
import requests
import socket
import shutil
import zipfile
import subprocess
def request(function,variable):
    url = (f"http://api.stines.de:8001/{function}")
    response = requests.post(url,json = variable,headers={'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'})
    return response

def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except Exception as e:
        print(f"Fehler beim Abrufen der lokalen IP-Adresse: {e}")
        return None

if not os.path.isfile("C:\Scripte\Alive-Check\.alive"):
        main_folder = "C:\Scripte\Alive-Check\\"
        try:
            os.mkdir(main_folder)
        except:
            print("Folder exist")
        shutil.copy("alive_check.exe",main_folder)
        response = requests.get("https://nssm.cc/release/nssm-2.24.zip", stream=True)
        with open('C:\Scripte\\nssm.zip', 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)

        # Entpacken der ZIP-Datei
        with zipfile.ZipFile('C:\Scripte\\nssm.zip', 'r') as zip_ref:
            zip_ref.extractall('C:\Scripte\\nssm')

        shutil.move("C:\Scripte\\nssm\\nssm-2.24\win64\\nssm.exe",f"{main_folder}Windows_Dienst_Builder.exe")
        os.system(f"{main_folder}Windows_Dienst_Builder.exe install STI-Alive-Check {main_folder}alive_check.exe")
        open(f"{main_folder}.alive", 'a').close()
        time.sleep(2)
        print("Remove not Used Files")
        shutil.rmtree('C:\Scripte\\nssm')
        os.remove('C:\Scripte\\nssm.zip')

while True:
    print(request("ping",{'name':str(socket.gethostname()),'ipaddress':get_local_ip()}).text)
    time.sleep(60)