/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: winstage1.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 "hxresult.h"
#include "wininstlib.h"
#include "bzlib.h"
#include "archive.h"

#include "stage1.h"
#include "winstage1.h"

WinStage1::WinStage1() : Stage1()
{
    memset(m_szArchiveDir, 0, MAX_PATH + 1);
}

WinStage1::~WinStage1()
{
}

/*
 * Loads a binary resource into pBuffer, and returns its size.
 */
UINT32
WinStage1::GetResource(const char* szName, BYTE*& pBuffer)
{    
    HRSRC hrsrc = FindResource(NULL, szName, "BINARY");	
    if(!hrsrc)
    {
	return 0;
    }

    HGLOBAL hgArchive = LoadResource(NULL, hrsrc);
    if(!hgArchive)
    {
	return 0;
    }

    UINT32 ulSize = SizeofResource(NULL, hrsrc);
    if(ulSize == 0)
    {
        return 0;
    }

    pBuffer = (BYTE*)LockResource(hgArchive);    
    if(pBuffer == NULL)
    {
        return 0;
    }

    return ulSize;
}

BOOL
WinStage1::MakeArchDir(void)
{
    // Create the temp directory for dearchiving
    UINT32 ulMaxDir = MAX_PATH - strlen(ARCHDIR) - 3;
    DWORD dwSize = GetTempPath(ulMaxDir, m_szArchiveDir);
    WIN32_FIND_DATA filedata;

    // Get current directory if temp failed
    if((!dwSize || dwSize >= ulMaxDir) && 
        !GetCurrentDirectory(ulMaxDir, m_szArchiveDir))
    {
        return FALSE;
    }

    strcat(m_szArchiveDir, ARCHDIR);
    char* szIndex = m_szArchiveDir + strlen(m_szArchiveDir);
    HANDLE hFindData;
    int i;

    // Check if the directory already exists, and if not, try to create it
    // Keep adding numbers until we can make the directory or get to 1000.    
    for(i = 0; i < 1000; i++)
    {
        hFindData = FindFirstFile(m_szArchiveDir, &filedata);
        if(hFindData == INVALID_HANDLE_VALUE)
        {
            if(CreateDirectory(m_szArchiveDir, NULL))
            {
                return TRUE;
            }
        }
        else
        {
            FindClose(hFindData);
        }
 
        // Add number and continue
        itoa(i, szIndex, 10);        
    }

    // Forget it, just go with the original
    szIndex[0] = '\0';
    RemoveDirRecursive(m_szArchiveDir);            
    return CreateDirectory(m_szArchiveDir, NULL);
}

HX_RESULT
WinStage1::Dearchive(BYTE* pArchive)
{
    if(strcmp(m_szArchiveType, "bz2") == 0)
    {
        return DearchiveBZ2(pArchive);
    }
    else
    {
        return HXR_INVALID_PARAMETER;
    }
}

HX_RESULT
WinStage1::DearchiveBZ2(BYTE* pArchive)
{
    HX_RESULT res = HXR_OK;
    bz_stream bzData;
    Dearchiver dearch;
    char pBZOut[DECOMPRESS_BUFFER_SIZE];
    UINT32 ulPos = 0;
    UINT32 ulData;
    BOOL bCancelled = FALSE;
    memset((void*) &bzData, 0, sizeof(bz_stream));
    bzData.next_out = (char*)pBZOut;
    bzData.avail_out = DECOMPRESS_BUFFER_SIZE;

    // init the decompressor
    int bzerr = BZ2_bzDecompressInit(&bzData, 0, 0);
    if(bzerr == BZ_OK)
    {
        res = dearch.Init(m_szArchiveDir);
    }
    while(bzerr == BZ_OK && SUCCEEDED(res) && res != HXR_CANCELLED)
    {
        if(bzData.avail_in == 0 && ulPos < m_ulArchiveSize)
        {
            // Move ahead to the next block
            bzData.next_in = (char*)pArchive + ulPos;
            bzData.avail_in = 
                ulPos + DECOMPRESS_BLOCK_SIZE > m_ulArchiveSize ? 
                m_ulArchiveSize - ulPos : DECOMPRESS_BLOCK_SIZE;
            ulPos += bzData.avail_in;
        }

        // Decompress
        bzerr = BZ2_bzDecompress(&bzData);

        // we hit the end of the buffer and it's not done decompressing
        if(ulPos >= m_ulArchiveSize && bzData.avail_in == 0 && 
            bzData.avail_out > 0 && bzerr != BZ_STREAM_END)
        {
            bzerr = BZ_UNEXPECTED_EOF;
        }

        // we've got some data, so let's untar it
        else if ((bzData.avail_out == 0 && bzerr == BZ_OK) ||
            bzerr == BZ_STREAM_END)
        {
            // untar it
            res = dearch.Extract((BYTE*)pBZOut, 
                DECOMPRESS_BUFFER_SIZE - bzData.avail_out, ulData);

            bzData.next_out = pBZOut;
            bzData.avail_out = DECOMPRESS_BUFFER_SIZE;
        }

        // Update the progress
        if(SUCCEEDED(res))
        {            
            res = UpdateProgress(ulPos);
        }
    }

    if(SUCCEEDED(res))
    {            
        res = UpdateProgress(m_ulArchiveSize);
    }

    // Cleanup the decompressor
    BZ2_bzDecompressEnd(&bzData);

    if(bzerr == BZ_MEM_ERROR)
    {
        return HXR_OUTOFMEMORY;
    }
    if(bzerr != BZ_STREAM_END && SUCCEEDED(res) && res != HXR_CANCELLED)
    {
        return HXR_FAIL;
    }

    return res;
}

HX_RESULT
WinStage1::RunSecondStage(void)
{
    char szCmd[MAX_PATH+1];
    snprintf(szCmd, MAX_PATH, "%s%c%s", m_szArchiveDir, OS_SEPARATOR_CHAR, 
            SECOND_STAGE_PROG);
    szCmd[MAX_PATH] = '\0';

    return RunSecondStageCmd(szCmd);
}
