#define WIN32_LEAN_AND_MEAN
#define STRICT
#include <windows.h>
#include <shellapi.h>

#include "../xvaga/incstr.h"
extern "C"        
{
#include "../xvaga/hlapi_c.h"
#include "../xvaga/skeylink.h"
}
#include <stdlib.h>
#include <string.h>
#include <time.h>

static HINSTANCE _hInstance = NULL;
static int _dongle_type = 0;

/****************************/
/* Utility */
/****************************/

void ErrorBox(LPCSTR str)
{
  MessageBox(GetFocus(), str, "Installazione", MB_ICONSTOP|MB_OK);
}

void WarningBox(LPCSTR str)
{
  MessageBox(GetFocus(), str, "Installazione", MB_ICONEXCLAMATION|MB_OK);
}

int ThisYear()
{  
  int anno = 2006;
  time_t lt;
  if (time(&lt) == 0) 
  {
    struct tm* timeloc = localtime(&lt) ;
    if (timeloc != NULL)
      anno = timeloc->tm_year + 1900;
  }
  return anno;
}

/****************************/
/* Gestione chiave Hardlock */
/****************************/

bool HardlockGarble(unsigned short* data)
{
  HL_CODE(data, 1);
  return TRUE;
}

unsigned short HardlockLogin(int& year)
{
  unsigned short serno = 0xFFFF;
  unsigned char REFKEY[16] = "CAMPOKEY";
  unsigned char VERKEY[16] = "�pو�c�<";
  if (HL_LOGIN(26952, LOCAL_DEVICE, REFKEY, VERKEY) == STATUS_OK)
  { 
    unsigned short eprom[64]; memset(eprom, 0, sizeof(eprom));
    HL_READBL((unsigned char*)eprom);
    unsigned short data[4];
    memcpy(data, eprom, sizeof(data));
    HardlockGarble(data);
    if (data[0] == 0xFAE8)
      serno = data[1];
    else  
      serno = 0;
      
    memcpy(data, &eprom[60], sizeof(data));
    if (HardlockGarble(data))
      year = (int)data[0];
  }
  return serno;
}

/**************************/
/* Gestione chiave Eutron */
/**************************/

void EncodeEutronPassword(char* str)
{
  const char* const key = "QSECOFR-";
  char tmp[16];
  int i;
  for (i = 0; str[i]; i++)
    tmp[i] = str[i] + (i < 8 ? key[i] : str[i - 8]);
  tmp[i] = '\0';
  strcpy(str, tmp);
}

unsigned short EutronLogin(int& year)
{
  unsigned short serno = 0xFFFF;
  
  const char* const login[2] = { "AGA.CAMPO", "25EBAI" };
  for (int i = 0; i < 2; i++)
  {
    KEY_NET eutron_key;
    memset(&eutron_key, 0, sizeof(KEY_NET));
    eutron_key.net_command = NET_KEY_OPEN;
    eutron_key.command = LOCATING_MODE;
  
    const char* const chiaro = login[i];
    char cifrato[16]; 
    strcpy(cifrato, chiaro);
    EncodeEutronPassword(cifrato);
  
    memset(eutron_key.label, 0, LABEL_LENGTH);
    strcpy((char*)eutron_key.label, chiaro);  
    memset(eutron_key.password, 0, PASSWORD_LENGTH);
    strcpy((char*)eutron_key.password, cifrato);  

    smartlink(&eutron_key);
    if (eutron_key.status == ST_OK)
    {
      eutron_key.net_command = NET_KEY_ACCESS;
      eutron_key.command = BLOCK_READING_MODE;
      short* pointer = (short*)(&eutron_key.data[0]);
      short* number  = (short*)(&eutron_key.data[2]);
      *pointer = 0; // Posizione in cui leggere
      *number = 8;  // Words da leggere
      smartlink(&eutron_key);
      if (eutron_key.status == ST_OK)
      {
        serno = (unsigned short)atol((const char*)eutron_key.data+4);
        if (i == 0)
        {
          const unsigned short y = *(unsigned short*)(eutron_key.data+12);
          if (y > 2000 && y < 3000)
            year = y;
        }
        else
          year = ThisYear();
        
        break;
      }
    }
  }  
  
  return serno;
}

/***********************************/
/* Gestione cifratura lista codici */
/***********************************/

void BuildKey(char* key)
{
  for (int i = 0; i < 8; i++)  
    key[i] = 'A'+ rand()%26;
}
  
void DecodeString(char* data)
{                             
  char key[8] = "";
  BuildKey(key);

  char tmp[256];
  int i;
  for (i = 0; data[i]; i++)
    tmp[i] = data[i] - (i < 8 ? key[i] : tmp[i - 8]);
  tmp[i] = '\0';
  strcpy(data, tmp); 
}

int VersionYear()
{                                                             
  char ver[32];
  GetPrivateProfileString("ba", "Versione", "", ver, sizeof(ver), "./program/zip/install.ini");
  ver[4] = '\0';
  return atoi(ver);
}

void ProgramName(char* name)
{
  char ver[80];
  GetPrivateProfileString("Main", "Producer", "", ver, sizeof(ver), "./program/zip/install.ini");

  if (ver[0] != '\0')
  {
    const char * const encryption_key = "QSECOFR-";
    int i;
    for (i = 0; ver[i]; i++)
      name[i] = ver[i] - (i < 8 ? encryption_key[i] : name[i - 8]);
    name[i] = '\0';
  }
  else
    strcpy(name, "Campo");
}

int DongleTest()
{ 
	_dongle_type = 0;
  int yearKey = 0;
  
  unsigned int serno = HardlockLogin(yearKey);
  if (serno == 0xFFFF)
	{
    serno = EutronLogin(yearKey);   
		if (serno != 0xFFFF)
			_dongle_type = 2;		//chiave eutron
	}
	else
		_dongle_type = 1;	//chiave hardlock
    
  if (serno == 0)	// Chiave di sviluppo
    return _dongle_type;          
	if (serno == 0xFFFF)	// Chiave inesistente o invisibile = Prima installazione o demo
		return  _dongle_type;
  
  const int verYear = VersionYear();
  if (yearKey < verYear) // Chiave gi� programmata con assistenza pagata
	{  
		bool ok = FALSE;
		ifstream keys("./program/zip/dninst.zip");
		if (keys.good())
		{
			char line[256];
			keys.getline(line, sizeof(line));
			srand(883);
			DecodeString(line);
			const int ass_year = atoi(line);
			if (ass_year > yearKey) // Non devo abbassare l'anno di assistenza!
			{
				srand(ass_year);
				while (!keys.eof())
				{
					keys.getline(line, sizeof(line));
					DecodeString(line);
					unsigned int sn = (unsigned int)atol(line);
					if (sn == serno || line[0] == '*')
					{
						ok = TRUE;
						break;
					}
				}
				if (ok)
				{
					const int n = ass_year%10;
					const int y = (ass_year / 1000) * 1000 + (ass_year%1000) /10;
					wsprintf(line, "Il contratto di manutenzione %d/%d verr� attivato automaticamente", y, n);
					WarningBox(line);
				}
				else  
				{
					wsprintf(line, "� necessario contattare l'assistenza tecnica\n"
												 "per l'abilitazione del contratto di manutenzione %d", verYear);
					WarningBox(line);
				}
			}
		} 
		else
		{
			ErrorBox("Impossibile verificare il contratto di manutenzione");
		}
	}
  return _dongle_type;
}

//allah!
int __stdcall DongleProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
	case WM_INITDIALOG:
		::CheckRadioButton(hDlg, 100, 101, 100);
		break;
	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case IDOK:
			_dongle_type = ::IsDlgButtonChecked(hDlg, 100) ? 2 : 1;
		case IDCANCEL:
			::EndDialog(hDlg, LOWORD(wParam));
			return true;
		default:
			break;
		}
		break;
	default:
		break;
	}
	return false;
}


bool InstallDongle()
{
	//metodo per richiedere il tipo di chiave e lanciare l'installazione dei servizi
	int ret = ::DialogBox(_hInstance, "DONGLE", NULL, DongleProc);
	if (ret != IDOK)
		return false;

	char path[256] = "";
	if (_dongle_type == 1)
		strcpy(path, "./chiavi/hardlock/hldrv32.exe");
	else
		strcpy(path, "./chiavi/eutron/sdi.exe");

	STARTUPINFO si;
  PROCESS_INFORMATION pi;

  ZeroMemory( &si, sizeof(si) );
  si.cb = sizeof(si);
  ZeroMemory( &pi, sizeof(pi) );

  // Start the child process. 
  if( !CreateProcess( NULL, // No module name (use command line). 
      path,							// Command line. 
      NULL,             // Process handle not inheritable. 
      NULL,             // Thread handle not inheritable. 
      FALSE,            // Set handle inheritance to FALSE. 
      0,                // No creation flags. 
      NULL,             // Use parent's environment block. 
      NULL,             // Use parent's starting directory. 
      &si,              // Pointer to STARTUPINFO structure.
      &pi )             // Pointer to PROCESS_INFORMATION structure.
  ) 
		return false;
  // Wait until child process exits.
  WaitForSingleObject( pi.hProcess, INFINITE );

  // Close process and thread handles. 
  CloseHandle( pi.hProcess );
  CloseHandle( pi.hThread );

	return true;
}

unsigned int Run(LPCSTR app)
{
  unsigned int ret = WinExec(app, SW_SHOWNORMAL);
  if (ret <= 32)
  {
    char s[128];
    wsprintf(s,"Impossibile eseguire\n%s\nErrore %d", app, (int)ret);
    ErrorBox(s);
  }
  return ret;
}

/* 
 * MainWndProc 
 * 
 * Purpose: 
 *  Window procedure for main window. The main window is a dialog. 
 * 
 */ 
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 
{ 
   switch (msg) 
   {                
    case WM_ERASEBKGND:
      {
        /* Repaint lo sfondo quando necessario*/
        HDC hdc = (HDC) wParam;
        HPEN hpenOld = (HPEN)SelectObject(hdc, GetStockObject(NULL_PEN));
        RECT rect; GetClientRect(hwnd,&rect); 

        COLORREF cStart = GetSysColor(COLOR_ACTIVECAPTION);
        COLORREF cStop = GetSysColor(27 /*COLOR_GRADIENTACTIVECAPTION*/);
        int deltaR = GetRValue(cStop) - GetRValue(cStart);
        int deltaG = GetGValue(cStop) - GetGValue(cStart);
        int deltaB = GetBValue(cStop) - GetBValue(cStart);

        const int ysize=rect.bottom-rect.top;
        const int step = 4;
        for (int y=rect.bottom; y>=rect.top-step; y-=step)
        {
          int r = GetRValue(cStart) + deltaR * y / rect.bottom;
          int g = GetGValue(cStart) + deltaG * y / rect.bottom;
          int b = GetBValue(cStart) + deltaB * y / rect.bottom;
          HBRUSH hbrush = CreateSolidBrush(RGB(r,g,b));
          HBRUSH hbrushOld = (HBRUSH)SelectObject(hdc, hbrush);
          Rectangle(hdc, rect.left, y, rect.right, y+step+1);
          SelectObject(hdc, hbrushOld);
          DeleteObject(hbrush);      
        }
        SelectObject(hdc, hpenOld);
      }
      break;
    case WM_PAINT:
      {
        PAINTSTRUCT ps;
        RECT rct;
        const char* s1 = "Installazione / Aggiornamento della versione normale";
        const char* s2 = "Installazione della versione dimostrativa";
        const char* s4 = "Termina installazione";
        const char* s5 = "Scelta installazione";
        
        HDC hdc = BeginPaint(hwnd, &ps);
        
        GetWindowRect(GetDesktopWindow(),&rct); 
        SetBkMode(hdc, TRANSPARENT);
        
        const int offx=(rct.right - rct.left-640)/2;
        const int offy=(rct.bottom - rct.top-260)/2;
        rct.left   = offx+300;
        rct.top    = offy;
        rct.right  = rct.left+350;
        rct.bottom = offy+60;

        SetTextColor(hdc, GetSysColor(COLOR_CAPTIONTEXT));
        DrawText(hdc, s1, strlen(s1), &rct, DT_LEFT|DT_WORDBREAK);
        rct.top += 80; rct.bottom += 80;
        DrawText(hdc, s2, strlen(s2), &rct, DT_LEFT|DT_WORDBREAK);
        rct.top += 80; rct.bottom += 80;
        DrawText(hdc, s4, strlen(s4), &rct, DT_LEFT|DT_WORDBREAK);
        
        /* Titolo con ombreggiatura */
        HFONT hfont = CreateFont(64, 0, 0, 0, FW_BOLD, TRUE, FALSE, FALSE, ANSI_CHARSET, OUT_TT_PRECIS, CLIP_TT_ALWAYS, PROOF_QUALITY, VARIABLE_PITCH | FF_SWISS, "Arial");
        HFONT hfontOld = (HFONT)SelectObject(hdc, hfont);
        
        SetTextColor(hdc, RGB(0,0,0));
        TextOut(hdc, 20, 20, s5, strlen(s5));

        SetTextColor(hdc, GetSysColor(COLOR_CAPTIONTEXT));
        TextOut(hdc, 16, 16, s5, strlen(s5));
        
        SelectObject(hdc, hfontOld);
        DeleteObject(hfont);
        EndPaint(hwnd, &ps);
      } 
      break;
    case WM_COMMAND:
      {
				bool quit_program = false;
				switch (LOWORD(wParam))
				{
				case 2:
					quit_program = true;
					break;
				case 1000:	//installazione normale con chiave
					if (_dongle_type == 0)	//non trova una chiave funzionante...
					{
						InstallDongle();	//chiede di installare la chiave...
						DongleTest();	//verifica l'installazione della chiave..
						if (_dongle_type == 0)	//la chiave non c'e' proprio!
						{	//forza l'installazione del modulo SY con chiave Eutron (finta)
							int ret = ::MessageBox(hwnd, "ATTENZIONE! Chiave di protezione NON rilevata:\n"
																					 "Si desidera installare ugualmente il modulo base ?",
																					 "Installazione", MB_YESNO | MB_ICONQUESTION);
							_dongle_type = ret == IDYES ? 2 : 0;
						}
					}
					if (_dongle_type != 0)
						quit_program = Run("program\\disk1\\setup.exe") > 32;
					break;
        case 1001: 
          quit_program = Run("demo\\disk1\\setup.exe") > 32;
					break;
        default:
					break;
				}
        if (quit_program)		//esce dal programma di installazione
					PostQuitMessage(0);
      }
      break;
    case WM_CHAR:
      if (wParam == VK_ESCAPE)
        PostQuitMessage(0);
      break;
    case WM_DESTROY:
      PostQuitMessage(0);
      break;
    default:
      return DefDlgProc(hwnd, msg, wParam, lParam);
   }

   return NULL;
}


/*
 * InitApplication
 *
 * Purpose:
 *  Registers window class
 *
 * Parameters:
 *  hinst       hInstance of application
 *
 * Return Value:
 *  TRUE if initialization succeeded, FALSE otherwise.
 */
BOOL InitApplication (HINSTANCE hinst)
{ 
   WNDCLASS wc; 
    
   wc.style = CS_DBLCLKS | CS_SAVEBITS | CS_BYTEALIGNWINDOW; 
   wc.lpfnWndProc = MainWndProc; 
   wc.cbClsExtra = 0; 
   wc.cbWndExtra = DLGWINDOWEXTRA; 
   wc.hInstance = hinst; 
   wc.hIcon = LoadIcon(hinst, MAKEINTRESOURCE(9012)); 
   wc.hCursor = LoadCursor(NULL, IDC_ARROW); 
   wc.hbrBackground = HBRUSH(COLOR_WINDOW + 1); 
   wc.lpszMenuName = NULL; 
   wc.lpszClassName = "MainWndClass";  
      
   return RegisterClass(&wc);         
} 
 
 
/* 
 * WinMain 
 * 
 * Purpose: 
 *  Main entry point of application.  
 * 
 */ 

int PASCAL WinMain (HINSTANCE hInst, HINSTANCE hinstPrev, LPSTR pCmdLine, int nCmdShow) 
{                
    if (!InitApplication(hInst)) // Register window class         
      return 0; 

		_hInstance = hInst;

		_dongle_type = DongleTest();	//controlla se la chiave c'e' ed eventualmente quale e'

    RECT rect;
    GetWindowRect(GetDesktopWindow(),&rect); 
    HWND hwndDlg=CreateWindow("MainWndClass","Scelta installazione",WS_VISIBLE| WS_CAPTION | WS_SYSMENU | WS_MAXIMIZE,
      rect.left,rect.top,rect.right,rect.bottom,NULL,NULL,hInst,NULL );

    const int offx=(rect.right - rect.left-700)/2;
    const int offy=(rect.bottom - rect.top-260)/2;

    char name[80];
    ProgramName(name);

    char prompt[128];
    strcpy(prompt, name);
    
		UINT dwFlags = WS_CHILD | WS_VISIBLE;
    /* Disegna i pulsanti */
    CreateWindow("BUTTON",prompt, dwFlags,
                 offx, offy, 300, 32, hwndDlg , (HMENU)1000, hInst, NULL );


		if (_dongle_type != 0)	//se la chiave e' presente e funzionante non si puo' installare la DEMO
			dwFlags |= WS_DISABLED;
    strcat(prompt, " DEMO");
    CreateWindow("BUTTON", prompt, dwFlags,
                 offx, offy+80, 300, 32, hwndDlg , (HMENU)1001, hInst, NULL );

    CreateWindow("BUTTON","Uscita",
      WS_CHILD| WS_VISIBLE,offx,offy+160,300,32, hwndDlg ,(HMENU)2,hInst,NULL );
    
    MSG msg; 
    while (GetMessage(&msg, NULL, 0, 0))
    { 
       TranslateMessage(&msg);
       DispatchMessage(&msg);
    }
    
    return (msg.wParam);
}