// RedirAppSync.cpp : Defines the exported functions for the DLL
//

#include "stdafx.h"

/*
 * Entry point called by ThinApp runtime when it needs to determine the
 * value of a Package.ini setting
 */
void __stdcall OnGetOption(BSTR OptionName, BSTR *OptionValue)
{
   // We're only interested in AppSync settings, leave others untouched
   if (_wcsnicmp(OptionName, L"AppSync", 7) != 0)
      return;

   // Override settings are stored in a file Overrides.ini in the same directory
   // as the virtual package. We retrieve the name of the virtual package using
   // the environment variable TS_ORIGIN (always set by ThinApp when running a
   // virtual app) and replace the file name part by Overrides.ini
   static LPWSTR IniName = NULL;
   if (IniName == NULL)
   {
      DWORD Size = GetEnvironmentVariableW(L"TS_ORIGIN", NULL, 0);
      if (Size == 0)
         return;
      IniName = new WCHAR[Size + 13];
      GetEnvironmentVariableW(L"TS_ORIGIN", IniName, Size);
      LPWSTR FilePart = PathFindFileNameW(IniName);
      wcscpy_s(FilePart, Size - (FilePart - IniName), L"Overrides.ini");
   }

   // Now try to read the override. If it's not there, GetPrivateProfileStringW
   // will return 0
   WCHAR Buffer[2048];
   DWORD Size = GetPrivateProfileStringW(L"BuildOptions", OptionName, NULL, Buffer, _countof(Buffer), IniName);
   if (Size != 0 && Size < _countof(Buffer) - 1)
   {
      // Change the value
      SysFreeString(*OptionValue);
      *OptionValue = SysAllocString(Buffer);
   }
}
