/*
 * PROJECT:        ReactOS Kernel
 * LICENSE:        GNU GPLv2 only as published by the Free Software Foundation
 * PURPOSE:        Reproduces issue
 * PROGRAMMERS:    Wim Hueskes (reactos@wimhueskes.eu)
 */

#include <windows.h>
#include <tchar.h>
#include <strsafe.h>

#define TESTFILE1 _T("TESTFILE.TXT")
#define TESTFILE2 _T("TESTFILE.~OL")
#define TESTWILDCARD _T("TESTFILE.*")

//#define TESTFILE1 _T("TEST FILE.TXT")
//#define TESTFILE2 _T("TEST FILE.~OL")
//#define TESTWILDCARD _T("TEST FILE.*")


// to display an unrelated error 
int Error(TCHAR *Message)
{
    _ftprintf(stderr, _T("Error: %s\n"), Message);
    return 255;
}

int CountFiles(TCHAR *Wildcard, TCHAR *FileName)
{
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind;
    int Count = 0;

    hFind = FindFirstFile(Wildcard, &FindFileData);
    if (hFind == INVALID_HANDLE_VALUE)
        return 0;

    do
    {
        _tprintf(_T("%s\n"), FindFileData.cFileName);
        if (_tcsicmp(FindFileData.cFileName, FileName) == 0)
            Count++;
    } while (FindNextFile(hFind, &FindFileData));

    FindClose(hFind);

    return Count;
}

int _tmain(int argc, _TCHAR *argv[])
{
    // Create a (new) testfile which we rename while still open
    HANDLE hFile = CreateFile(TESTFILE1, GENERIC_WRITE, FILE_SHARE_DELETE, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
        return Error(_T("CreateFile"));

    // make sure TESTFILE2 does not exist
    DeleteFile(TESTFILE2);

    // rename TESTFILE1
    if (!MoveFile(TESTFILE1, TESTFILE2))
        return Error(_T("MoveFile"));

    // this would verify the file has been renamed
    if (CountFiles(TESTWILDCARD, TESTFILE2) != 1) 
        return Error(_T("Verify"));

    // Change attributes of the backup copy
    if (!SetFileAttributes(TESTFILE2, FILE_ATTRIBUTE_NORMAL))
        return Error(_T("SetFileAttributes"));

    // now close file
    CloseHandle(hFile);

    if (CountFiles(TESTWILDCARD, TESTFILE2) != 1) {
        _ftprintf(stderr, _T("%s has disappeared!\n"), TESTFILE2);
        return 1;
    }
    return 0;
}
 
