#include <windows.h>
#include <stdio.h>
#include <detours.h>
#pragma comment(lib,"detours.lib")
#pragma comment(lib,"msvcrt.lib")

void LaunchShit(void);

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static HWND hButton;
    switch(msg)
    {
		
		case WM_CREATE:
		{	
			hButton = CreateWindow("BUTTON", "&DO IT", WS_VISIBLE | WS_CHILD, 150, 150, 80, 50, hwnd, NULL, GetModuleHandle(NULL), NULL);
		}
		break;
		case WM_COMMAND:
		if ((HWND)lParam == hButton)
		{
			MessageBox(0, "Launching detoured program", "Information", MB_OK | MB_ICONINFORMATION);
			LaunchShit();
		}
		break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
	
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 1;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = NULL;

	char mystr[9];
	char name2[9];
	DWORD kek = GetTickCount();
	sprintf(mystr,"%x",kek);
	// random window name
	int kk = rand() % (256 - 64 + 1) + 64;
	__asm
	{
		xor ecx,ecx
		mov ecx,kk
		next:
		fnop
		nop
		loop next
	}
	// random stall for to ensure window name and title are different 
	DWORD rekt = GetTickCount();
	sprintf(name2,"%x",rekt);

	// ^^ random class name please :)
    wc.lpszClassName = mystr;
    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

    if(!RegisterClassEx(&wc))
    {
        return 0;
    }
    hwnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, mystr, name2, WS_VISIBLE | WS_SYSMENU, 200, 200, 350, 350, NULL, NULL, hInstance, NULL);



    if(hwnd == NULL)
    {
        return 0;
    }

   // ShowWindow(hwnd, SW_HIDE);
    UpdateWindow(hwnd);
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

void LaunchShit(void)
{
char *prog = "qbittorrent.exe";
	
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	ZeroMemory(&si, sizeof(si));
	ZeroMemory(&pi, sizeof(pi));
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESHOWWINDOW;
	si.wShowWindow = SW_SHOW;
	if (!DetourCreateProcessWithDllEx(prog,
		NULL, NULL, NULL, TRUE,
		CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED,
		NULL, NULL, &si, &pi,
		"Detoured_1.dll", NULL))
	{
		MessageBox(0, "failed", 0, 0);
		return ;
	}
	else
	{
		ResumeThread(pi.hThread);

		WaitForSingleObject(pi.hProcess, INFINITE);

		CloseHandle(&si);
		CloseHandle(&pi);
	}


        
}
