import requests
import subprocess
import socket
import json
from datetime import datetime

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('"','')

# PowerShell-Skript für die Active Directory-Abfrage
# powershell_script = r'''
# # PowerShell-Skript für die Active Directory-Abfrage mit Filter
# $ADResults = Get-ADUser -Filter { (ObjectClass -eq "user") -and (-not (UserPrincipalName -like "*Mailbox*")) -and (-not (UserPrincipalName -like "*Admin*")) -and (-not (UserPrincipalName -like "*Exchange*"))} -Properties SamAccountName | Select-Object SamAccountName
#
# # Ausgabe der JSON-Daten
# $ADResults | ConvertTo-Json | Out-File -FilePath "disable_user.json" -Encoding UTF8
# '''

def datum_in_filetime(used_date):
    jahr = used_date.year
    monat = used_date.month
    datum = datetime(jahr, monat + 1, 1) if monat < 12 else datetime(jahr + 1, 1, 1)
    return datum

print("FileTime-Wert für den ersten Tag des nächsten Monats:", datum_in_filetime(datetime(2023, 3, 23)))


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

with open('disable_user.json', 'r',encoding='utf-8-sig') as file:
    ad_data = json.load(file)

# Ergebnisse anzeigen oder weiterverarbeiten
    for entry in ad_data:
        samaccountname = entry['SamAccountName']
        print(samaccountname)
        user_disabled = request("/ad/user/disabled", {"user": f'{samaccountname}', "dbname": getdabase()}).json()
        print(user_disabled)
        count = 0
        for i in user_disabled:
            datum = i[1]
            if datum is None:
                next
            else:
                date_str = datetime.fromisoformat(str(datum))
                datum = date_str.strftime("%d.%m.%Y")
            gruppen = i[0]
            if datum is None:
                next
            else:
                print(f"{datum} - {gruppen} - {samaccountname}")
                print(subprocess.run(["powershell", "-command", f"Remove-ADGroupMember -Identity '{gruppen}' -Members '{samaccountname}' -Confirm:$False"]))
                if gruppen == "G-RDP-User":
                    count +=1
                    print(subprocess.run(["powershell", "-command", f"Set-ADUser -Identity '{samaccountname}'" "-Replace @{extensionAttribute1 = 'RDS - Deaktiviert am: "f'{datum}'"'} -Confirm:$False"]))
                if gruppen == "G-Exchange-User":
                    count +=1
                    print(subprocess.run(["powershell", "-command",
                                    f"Set-ADUser -Identity '{samaccountname}'" "-Replace @{extensionAttribute2 = 'Exchange - Deaktiviert am: "f'{datum}'"'} -Confirm:$False"]))
                if count == 2:
                    print(count)