# Fetch password from ITSM
password = itsm.getParameter('DummyPassword')

import _winreg
import os
import subprocess

# --- Registry (lock screen message) ---
try:
    Key = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
    Registrykey = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, Key)
    _winreg.SetValueEx(Registrykey, "legalnoticecaption", 0, _winreg.REG_SZ, "Warning")
    _winreg.SetValueEx(
        Registrykey,
        "legalnoticetext",
        0,
        _winreg.REG_SZ,
        "The machine has been lost/stolen. Contact your system Administrator."
    )
    _winreg.CloseKey(Registrykey)
    print "Lock screen message applied"
except WindowsError as e:
    print "Error setting registry:", e


# --- Local account password reset ---
try:
    cmd = "net user"
    obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = obj.communicate()

    users = []
    collecting = False
    for line in out.splitlines():
        if "----" in line:  # start/stop collecting after dashed line
            collecting = not collecting
            continue
        if collecting:
            if "The command completed" in line:  # stop at footer
                break
            parts = line.split()
            for p in parts:
                if p.lower() not in ["administrator", "guest", "defaultaccount", "wdagutilityaccount"]:
                    users.append(p.strip())

    print "Users found:", users

    for u in users:
        print "Trying to reset password for:", u
        cmd = 'net user "%s" "%s"' % (u, password)
        obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = obj.communicate()

        if "The command completed successfully" in out:
            print "Password changed successfully for:", u
        else:
            print "FAILED for:", u
            print "  STDOUT:", out
            print "  STDERR:", err

except Exception as e:
    print "Password reset section failed:", str(e)


# --- Restart machine ---
print "Restarting machine to apply changes..."
os.popen("shutdown.exe -r -t 5")
