#include <windows.h>
#include <stdio.h>

// Function to enable the SE_SHUTDOWN_NAME privilege
BOOL EnableShutdownPrivilege() {
    HANDLE hToken;
    LUID luid;
    TOKEN_PRIVILEGES tkp;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
        return FALSE;
    }

    if (!LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &luid)) {
        CloseHandle(hToken);
        return FALSE;
    }

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = luid;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0)) {
        CloseHandle(hToken);
        return FALSE;
    }

    CloseHandle(hToken);
    return TRUE;
}

int main() {
    if (!EnableShutdownPrivilege()) {
        printf("Failed to enable shutdown privilege. Error: %lu\n", GetLastError());
        return 1;
    }

    printf("Shutdown privilege enabled. Attempting to shut down the system...\n");

    // Shut down the system, force applications to close, and power off the computer
    if (ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCEIFHUNG, SHTDN_REASON_FLAG_PLANNED)) {
        printf("Shutdown initiated successfully.\n");
    } else {
        printf("Failed to initiate shutdown. Error: %lu\n", GetLastError());
        return 1;
    }

    // The system will shut down if successful. This part might not be reached.
    return 0;
}
