/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: wininstlib.cpp,v 1.1.2.1 2004/07/09 02:03:06 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

#include "hxtypes.h"
#include <windows.h>
#include <stdio.h>
#include <shlobj.h>
#include <intshcut.h>

#include "wininstlib.h"

/*
 * RemoveDirRecursive - (rm -r *) recursively removes directory and 
 * all contents.
 */
BOOL
RemoveDirRecursive(const char* szDir)
{
    size_t nLen = strlen(szDir);
    if(nLen > MAX_PATH-2)
    {
        // This directory name is too long to contain files!
        // Just try to remove it as is
        return RemoveDirectory(szDir);
    }
    
    WIN32_FIND_DATA findData;
    char szFileDesc[MAX_PATH+1];

    sprintf(szFileDesc, "%s%c*", szDir, OS_SEPARATOR_CHAR);
    HANDLE hFindFile = FindFirstFile(szFileDesc, &findData);    

    if(hFindFile != INVALID_HANDLE_VALUE)
    {
        // Delete all the files and subdirectories
        do
        {
            // Skip "." and "..". 
            if(nLen + strlen(findData.cFileName) < MAX_PATH
                && strcmp(findData.cFileName, ".") != 0 
                && strcmp(findData.cFileName, "..") != 0)
            {
                sprintf(szFileDesc, "%s%c%s", szDir, OS_SEPARATOR_CHAR,
                        findData.cFileName);
                
                // Remove directory
                if(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                {
                    RemoveDirRecursive(szFileDesc);
                }
                // Delete file
                else
                {
                    DeleteFile(szFileDesc);
                }
            }

        } while(FindNextFile(hFindFile, &findData));

        FindClose(hFindFile);
    }
    
    return RemoveDirectory(szDir);
}

/*
 * ReplaceOnReboot - Replace szFile with szNewFile on reboot. 
 * If szNewFile is NULL, szFile is deleted on reboot.
 * Implemented for NT systems only. Does nothing on 9x.
 */
BOOL ReplaceOnReboot(const char* szFile, const char* szNewFile)
{
    // Mark the file for replacement or removal on reboot (NT only)
    OSVERSIONINFO osinfo;
    osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);            
    if(GetVersionEx(&osinfo) && 
        osinfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
    {                
        return MoveFileEx(szFile, szNewFile, MOVEFILE_DELAY_UNTIL_REBOOT);
    }

    return FALSE;
}

/*
 * ConvertCmdLine - converts Windows style command line to a normal
 * argv style, but leaves argv[0] NULL.
 */
void
ConvertCmdLine(LPSTR lpCmdLine, int& argc, char**& argv)
{    
    if(!lpCmdLine)
    {
        argc = 1;
        argv = new char*[2];
        if(argv)
        {
            argv[0] = NULL;
            argv[1] = NULL;        
        }
        return;
    }

    char*   pCmdEnd;        
    char*   pArg;
    BOOL    bInQuote = FALSE;
    BOOL    bEndArg = FALSE;    

    // Skip any initial space. Shouldn't happen
    for(;*lpCmdLine != '\0' && isspace(*lpCmdLine); lpCmdLine++);

    argc = 1;
    
    // Find out how many args
    for(pCmdEnd = lpCmdLine; *pCmdEnd != '\0'; pCmdEnd++)
    {
        if(*pCmdEnd == '\"')
        {
            bEndArg = bInQuote;
            bInQuote = !bInQuote;
        }
        else if((!bInQuote && isspace(*pCmdEnd)) || *(pCmdEnd+1) == '\0')
        {
            bEndArg = TRUE;
        }
        if(bEndArg)
        {
            argc++;

            // Skip any extra spaces
            for(;*(pCmdEnd+1) != '\0' && isspace(*(pCmdEnd+1)); pCmdEnd++);

            bEndArg = FALSE;
        }
    }

    // Make argv and fill it
    argv = new char*[argc+1];
    if(!argv)
    {
        argc = 0;
        return;
    }

    // First arg is for the command.
    argv[0] = NULL;    
    
    bEndArg = FALSE;
    size_t nArgLen = 0;
    
    int i = 1;    

    if(argc > 1)
    {
        for(i = 1, pArg = pCmdEnd = lpCmdLine; 
            i < argc && *pCmdEnd != '\0'; pCmdEnd++)
        {
            if(*pCmdEnd == '\"')
            {
                if(!bInQuote)
                {
                    // Start quote. Advance the arg pointer.
                    pArg++;
                    bInQuote = TRUE;
                }
                else
                {
                    // End quote.
                    bEndArg = TRUE;
                    bInQuote = FALSE;
                    nArgLen = pCmdEnd - pArg;
                }
            }
            else if(!bInQuote && isspace(*pCmdEnd))
            {
                bEndArg = TRUE;
                nArgLen = pCmdEnd - pArg;
            }
            else if(*(pCmdEnd+1) == '\0')
            {
                bEndArg = TRUE;
                nArgLen = pCmdEnd + 1 - pArg;
            }
            if(bEndArg)
            {
                // Create and copy the arg
                argv[i] = new char[nArgLen+1];
                if(argv[i])
                {
                    strncpy(argv[i], pArg, nArgLen);
                    argv[i][nArgLen] = '\0';
                }

                // Skip any extra space
                for(;*(pCmdEnd+1) != '\0' && isspace(*(pCmdEnd+1)); pCmdEnd++);

                pArg = pCmdEnd+1;
                i++;

                bEndArg = FALSE;
            }
        }
    }
    
    // Last arg is NULL
    for(;i <= argc; i++)
    {
        argv[i] = NULL;            
    }
}

/*
 * GetRegString - Reads a string value from the registry
 */
BOOL
GetRegString(HKEY hkeyRoot, const char* szKey, const char* szSubKey, 
             char* szValue, UINT32 ulValLen)
{
    HKEY hKey;
    LONG res;
    DWORD dwSize = ulValLen;
    DWORD dwType;    
   
    // Open the key
    res = RegOpenKeyEx(hkeyRoot, szKey, 0, KEY_READ, &hKey);
    if(res != ERROR_SUCCESS)
    {
        return FALSE;
    }

    dwSize = ulValLen;

    // Get the value
    res = RegQueryValueEx(hKey, szSubKey, NULL, &dwType,
            (LPBYTE)szValue, &dwSize);

    RegCloseKey(hKey);

    return res == ERROR_SUCCESS && dwType == REG_SZ ? TRUE : FALSE;
}

/*
 * WriteRegString - writes a string vaue to the registry
 */
BOOL 
WriteRegString(HKEY hkeyRoot, const char* szKey, const char* szSubKey,
               const char* szValue)
{
    HKEY hKey;
    LONG res;    
    DWORD dwDisposition;

    // Create and/or open the key
    res = RegCreateKeyEx(hkeyRoot, szKey, 0, "", 0, KEY_WRITE, NULL, &hKey,
                        &dwDisposition);

    if(res != ERROR_SUCCESS)
    {
        return FALSE;
    }

    // Set the value
    res = RegSetValueEx(hKey,szSubKey, 0, REG_SZ, (const BYTE*)szValue,
                        (DWORD)(strlen(szValue) + 1));

    RegCloseKey(hKey);

    return res == ERROR_SUCCESS ? TRUE : FALSE;
}
