// WaitForReboot.cpp : implementation file
//

#include "stdafx.h"
#include "WaitForReboot.h"
#include "StartProcCmdLineInfo.h"


// CWaitForRebootApp

IMPLEMENT_DYNCREATE(CWaitForRebootApp, CWinApp)

CWaitForRebootApp::CWaitForRebootApp()
    : m_dwWaitedProcessId(0)
{
}

CWaitForRebootApp::~CWaitForRebootApp()
{
}

BOOL CWaitForRebootApp::InitInstance()
{
    CStartProcCmdLineInfo   oStartProcCmdLineInfo;
    HANDLE                  hWaitedProcessHandle;
    BOOL                    bRet;
    DWORD                   dwWaitResult;
    HANDLE                  hToken;
    TOKEN_PRIVILEGES        stTkp;
    ParseCommandLine(oStartProcCmdLineInfo);
    hWaitedProcessHandle = OpenProcess(
        PROCESS_ALL_ACCESS,
        FALSE,
        m_dwWaitedProcessId
        );
    ASSERT(NULL != hWaitedProcessHandle);
    dwWaitResult = WaitForSingleObject(
        hWaitedProcessHandle,
        INFINITE
        );
    ASSERT(WAIT_OBJECT_0 == dwWaitResult);
    bRet = CloseHandle(hWaitedProcessHandle);
    bRet = OpenProcessToken(
        GetCurrentProcess(),
        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
        &hToken
        );
    ASSERT(bRet);
    bRet = LookupPrivilegeValue(
        NULL,
        SE_SHUTDOWN_NAME,
        &stTkp.Privileges[0].Luid
        );
    ASSERT(bRet);
    stTkp.PrivilegeCount = 1;
    stTkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    bRet = AdjustTokenPrivileges(
        hToken,
        FALSE,
        &stTkp,
        0,
        (PTOKEN_PRIVILEGES)NULL,
        (PDWORD)NULL
        );
    ASSERT(bRet);
    bRet = CloseHandle(hToken);
    bRet = ExitWindowsEx(
        EWX_REBOOT,
        SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_MAINTENANCE | SHTDN_REASON_FLAG_PLANNED
        );
    ASSERT(bRet);
    return FALSE;
}

int CWaitForRebootApp::ExitInstance()
{
	return CWinApp::ExitInstance();
}

BEGIN_MESSAGE_MAP(CWaitForRebootApp, CWinApp)
END_MESSAGE_MAP()

CWaitForRebootApp theApp;

// CWaitForRebootApp message handlers
