/* (C) 2003-2007 Willem Jan Hengeveld <itsme@xs4all.nl>
 * Web: http://www.xs4all.nl/~itsme/
 *      http://wiki.xda-developers.com/
 *
 * $Id$
 */
// 'prmdir' == pdel
#include <util/wintypes.h>
#include <stdio.h>
#include <string.h>
#include <util/rapitypes.h>

#include "debug.h"
#include "args.h"

#include "vectorutils.h"
#include "stringutils.h"
#include <map>
#include "csidlpaths.h"

bool g_bRecurse= false;

typedef std::map<std::string,std::string> StringStringMap;

#define AT_NONEXISTANT      1
#define AT_ISDIRECTORY      2
#define AT_ISFILE           3

int getCeAttributes(const std::string& name)
{
    DWORD dwAttr = CeGetFileAttributes( expand_csidl(ToWString(name)).c_str() );
    if (0xFFFFFFFF == dwAttr)
        return AT_NONEXISTANT;

    if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
        return AT_ISDIRECTORY;

    return AT_ISFILE;
}
bool isCeDirectory(const std::string& name)
{
    return getCeAttributes(name)==AT_ISDIRECTORY;
}
bool isCeFile(const std::string& name)
{
    return getCeAttributes(name)==AT_ISFILE;
}
bool isCeNonExistant(const std::string& name)
{
    return getCeAttributes(name)==AT_NONEXISTANT;
}
std::string concat_path(const std::string& p1, const std::string& p2)
{
    std::string result(p1);

    if (result.size() && result[result.size()-1]!='/' && result[result.size()-1]!='\\')
        result += '\\';

    result += p2;

    return result;
}

std::string GetBasePath(const std::string& name)
{
    size_t lastslash= name.find_last_of("\\/");
    if (lastslash==name.npos)
        return "";

    return name.substr(0, lastslash);
}
bool MakeCeDirectory(const std::string& name)
{
    size_t pos= name.find_first_of("\\/");

    while (true)
    {
        std::string path= name.substr(0, pos);
        if (isCeFile(path)) {
            debug("ERROR: %s is a file\n", path.c_str());
            return false;
        }
        if (isCeNonExistant(path)) {
            if (!CeCreateDirectory(expand_csidl(ToWString(path)).c_str(), NULL))
            {
                ceerror("CeCreateDirectory(%s)", path.c_str());
                return false;
            }
        }
        if (pos==name.npos)
            break;
        pos= name.find_first_of("\\/", pos+1);
    }
    return true;
}

void usage()
{
    printf("(C) 2003-2008 Willem jan Hengeveld  itsme@xs4all.nl\n");
    printf("Usage: pmkdir dir ...\n");
}
int main( int argc, char *argv[])
{
    DebugStdOut();

    StringList dirlist;

    for (int i=1 ; i<argc ; i++)
    {
        if (argv[i][0]=='-') switch(argv[i][1])
        {
            default:
                usage();
                return 1;
        }
        else
        {
            dirlist.push_back(argv[i]);
        }
    }
    if (FAILED(CeRapiInit()))
    {
        printf( "Failed\n");
        return 1;
    }

    for (StringList::iterator i= dirlist.begin() ; i!=dirlist.end(); ++i)
        MakeCeDirectory(*i);

    CeRapiUninit();
}

