import subprocess
import json
import requests
import socket


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

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 getdabase():
    r = request("/info/getdatabase",{'ip':get_local_ip()})
    return r.text.replace('"','')

def server_exist(hostname):
    return request("/info/getserver",{'name': hostname, 'dbase': getdabase()})

# PowerShell-Skript zum Abrufen von Gruppen und Mitgliedern aus Active Directory
powershell_script = r'''
# Gruppen abrufen, deren Name mit "G-" beginnt
$groups = Get-ADGroup -Filter {Name -like "G-*"} | ForEach-Object {
    $group = $_
    $members = Get-ADGroupMember -Identity $group
    [PSCustomObject]@{
        GroupName = $group.Name
        Members = $members.SamAccountName
    }
}

# Das Ergebnis in JSON exportieren
$groups | ConvertTo-Json | Out-File -FilePath "group_members.json" -Encoding UTF8

'''

# PowerShell-Skript ausführen und die Ausgabe abrufen
result = subprocess.run(["powershell", "-command", powershell_script], stdout=subprocess.PIPE, text=True)

# Die JSON-Ausgabe parsen
with open('group_members.json', 'r', encoding='utf-8-sig') as file:
    group_data = json.load(file)

# Iterieren Sie über die Gruppen und ihre Mitglieder und zeigen Sie sie an
for group_entry in group_data:
    group_name = group_entry['GroupName']
    members = group_entry['Members']
    #
    if isinstance(members, list):
        for member in members:
            addusertogroup = request("/report/addusertogroup", {'member': member, "groupname": group_name, 'dbname': getdabase()})
            print(addusertogroup.text)
            if addusertogroup.text == "false":
                next