/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: hxar.cpp,v 1.1.2.1 2004/07/09 02:02:36 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 "hxresult.h"

#include <stdio.h>
#include <io.h>
#include <fcntl.h>

#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#else
#include <sys/types.h>
#endif

#include "archive.h"

#define HXMODE_CREATE   0
#define HXMODE_EXTRACT  1

#define STR_OPTIONS_NEEDS_ARG "option %s requires an argument\n"

HX_RESULT 
Archive(FILE* fTarFile, char** pFileList, int nNumFiles)
{
    HX_RESULT res = HXR_OK;
    FILE* fOutFile = NULL;    
    Archiver tarFile;

    if(!pFileList || !nNumFiles)
    {
        fprintf(stderr, "you must specify at least one file to archive\n");
        return HXR_FAIL;
    }

    res = tarFile.Init(fTarFile);
    if(FAILED(res))
    {
        fprintf(stderr, "error: could not write to output file.\n");
    }

    for(int i = 0; i < nNumFiles && SUCCEEDED(res); i++)
    {
        res = tarFile.AddFile(pFileList[i]);
        if(FAILED(res))
        {
            fprintf(stderr, "error: could not add file \"%s\".\n", 
                pFileList[i]);
        }
    }

    if(fTarFile)
    {
        fclose(fTarFile);
    }

    return res;
}

HX_RESULT
Dearchive(FILE* fTarFile)
{
    HX_RESULT res = HXR_OK;
    FILE* fInFile = NULL;
    Dearchiver dearch;

    res = dearch.Init();
    if(FAILED(res))
    {
        fprintf(stderr, "error: could not write to output directory.\n");
    }
    else
    {
        res = dearch.Extract(fTarFile);
    }

    if(fInFile)
    {
        fclose(fTarFile);
    }

    return res;
}

HX_RESULT
OpenOutputFile(const char* szTarFileName, FILE*& fFile)
{
    if(szTarFileName)
    {
        fFile = fopen(szTarFileName, "wb");
        if(!fFile)
        {
            fprintf(stderr, "error: could not open output file %s\n", 
                szTarFileName);
            return HXR_WRITE_ERROR;
        }
    }
    else
    {
        fFile = stdout;
        if(setmode(fileno(stdout), _O_BINARY) < 0)
        {
            fprintf(stderr, "error: could not access stdout.\n");
            return HXR_UNEXPECTED;
        }
    }

    return HXR_OK;
}

HX_RESULT
OpenInputFile(const char* szTarFileName, FILE*& fFile)
{
    if(szTarFileName)
    {
        fFile = fopen(szTarFileName, "rb");
        if(!fFile)
        {
            fprintf(stderr, "error: could not open input file %s\n", 
                szTarFileName);
            return HXR_FILE_NOT_FOUND;
        }
    }
    else
    {
        fFile = stdin;
        if(setmode(fileno(stdin), _O_BINARY) < 0)
        {
            fprintf(stderr, "error: could not access stdin.\n");
            return HXR_UNEXPECTED;
        }
    }

    return HXR_OK;
}

int main(int argc, char* argv[])
{
    int nMode = -1;
    const char* szTarFileName = NULL;
    const char* szDir = NULL;
    FILE* fTarFile = NULL;
    char szCWD[MAX_PATH + 1];
    char** pFileList = NULL;
    int nNumFiles = 0;
    HX_RESULT res = HXR_OK;
    int i;

    // Parse the command line
    for (i = 1; i < argc; i++)
    {
        if (strcmp(argv[i], "-c") == 0 ||
            strcmp(argv[i], "--create") == 0)
        {
            nMode = HXMODE_CREATE;
        }
        else if (strcmp(argv[i], "-x") == 0 ||
                strcmp(argv[i], "--extract") == 0)
        {
            nMode = HXMODE_EXTRACT;
        }
        else if (strncmp(argv[i], "-f", 2) == 0)
        {
            if(argv[i][2] != '\0')
            {
                szTarFileName = argv[i] + 2;
            }
            else if(i + 1 < argc && argv[i+1][0] != '-')
            {
                szTarFileName = argv[++i];
            }
            else
            {
                fprintf(stderr, STR_OPTIONS_NEEDS_ARG, argv[i]);
                return HXR_FAIL;
            }
        }
        else if (strncmp(argv[i], "--file", 6) == 0)
        {
            if (argv[i][6] == '=' && argv[i][7] != '\0')
            {
                szTarFileName = argv[i] + 7;
            }
            else if (i + 1 < argc && argv[i+1][0] != '-')
            {
                szTarFileName = argv[++i];
            }
            else
            {
                fprintf(stderr, STR_OPTIONS_NEEDS_ARG, argv[i]);
                return HXR_FAIL;
            }
        }
        else if (strncmp(argv[i], "-C", 2) == 0)
        {
            if(argv[i][2] != '\0')
            {
                szDir = argv[i] + 2;
            }
            else if(i + 1 < argc && argv[i+1][0] != '-')
            {
                szDir = argv[++i];
            }
            else
            {
                fprintf(stderr, STR_OPTIONS_NEEDS_ARG, argv[i]);
                return HXR_FAIL;
            }
        }
        else if (argv[i][0] != '-')
        {
            pFileList = &argv[i];
            nNumFiles = argc - i;
            break;
        }
        else
        {
            fprintf(stderr, "unknown option: %s\n", argv[i]);
            return HXR_FAIL;
        }
    }

    switch(nMode)
    {
        case(HXMODE_CREATE):
        {
            res = OpenOutputFile(szTarFileName, fTarFile);
        }
        break;
        case(HXMODE_EXTRACT):
        {
            res = OpenInputFile(szTarFileName, fTarFile);
        }
        break;
        default:
        {
            fprintf(stderr, "you must specify -c or -x\n");
            return HXR_FAIL;
        }
    }

    // save the current working directory and cd to the new one
    if(szDir)
    {
        if(!getcwd(szCWD, MAX_PATH))
        {
            fprintf(stderr, 
                "error: could not find current working directory\n");
            res = HXR_FAIL;
        }

        else if(chdir(szDir) != 0)
        {
            fprintf(stderr, "error: could not find directory %s\n", szDir);
            res = HXR_FILE_NOT_FOUND;
        }
    }


    switch(nMode)
    {
        case(HXMODE_CREATE):
        {
            res = Archive(fTarFile, pFileList, nNumFiles);
        }
        break;
        case(HXMODE_EXTRACT):
        {
            res = Dearchive(fTarFile);
        }
        break;        
    }

    // change back to the original directory
    if(szDir)
    {
        chdir(szCWD);
    }

    return res;
}
