CSS_RETRY_COUNT = 6;
SWDL_RETRY_COUNT = 1;
CSS_SLEEP_TIME = 30000;
SWDL_SLEEP_TIME = 0;
CSS_APPLCIATION = 'CSS'
CSS_PRODUCTNAME = 'Configuration_Service_Software'
SWDL_APPLICATION = 'SWDL'
SWDL_PRODUCTNAME = 'Software_Download_Manager'
CSS_LOCK_NAME_PATTERN = /^write_lock\d+\.lck/;
SWDL_LOCK_NAME_PATTERN = /^operationlock$/;
LOG_FILE_PATH_PREFIX = 'C:\\Windows\\Debug\\Motorola_'
LOG_FILE_PATH_SUFFIX = '_operationInProgressCheck.log';
var LOG_FILE_PATH ;
// w swdl ma nie czekeac

function checkIfNoWriteOperationInProgessExists(application, release) {
	var activeXObject = new ActiveXObject("Scripting.FileSystemObject");
	eval(activeXObject.OpenTextFile('systemServices.js', 1).ReadAll());
	var folder, retryCount, sleepTime, lockNamePattern;
	try {
		switch(application){
			case CSS_APPLCIATION :
				LOG_FILE_PATH = LOG_FILE_PATH_PREFIX + CSS_PRODUCTNAME + '_A' + release + LOG_FILE_PATH_SUFFIX;
				folder = activeXObject.GetFolder(getTmpDir(release));
				retryCount = CSS_RETRY_COUNT;
				sleepTime = CSS_SLEEP_TIME;
				lockNamePattern = CSS_LOCK_NAME_PATTERN;
				break;
			case SWDL_APPLICATION :
				LOG_FILE_PATH = LOG_FILE_PATH_PREFIX + SWDL_PRODUCTNAME + '_A' + release + LOG_FILE_PATH_SUFFIX;
				folder = activeXObject.GetFolder(getSWDLTmpPath(release));
				retryCount = SWDL_RETRY_COUNT;
				sleepTime = SWDL_SLEEP_TIME;
				lockNamePattern = SWDL_LOCK_NAME_PATTERN;
				break;
			default :
				// function not properly used
				return false;
		}
	}catch(exception) {
		// locks directory does not exist
		log(LOG_FILE_PATH, 'There is no lock file directory so there is no operation in progress which should be completed'); 
		return true;
	}
	count = 0;
	while(count < retryCount && !removeAllLockFiles(folder, lockNamePattern)) {
		count++;
		if(count < retryCount) {
			log(LOG_FILE_PATH, 'Awaiting for the next attempt for ' + sleepTime + 'ms. Remaining attempts count - ' + (retryCount  - count))
			WScript.Sleep(sleepTime);
		}
	}
	return count < retryCount;
}

function removeAllLockFiles(folder, lockNamePattern) {
	var activeXObject = new ActiveXObject("Scripting.FileSystemObject");
	eval(activeXObject.OpenTextFile('systemServices.js', 1).ReadAll());
	var enumFiles = new Enumerator(folder.files);
	for (; !enumFiles.atEnd(); enumFiles.moveNext()){
		var file = enumFiles.item();
		if(lockNamePattern.test(file.name)) {
			var path = file.path;
			try {
				activeXObject.DeleteFile(path);
				log(LOG_FILE_PATH, 'Lock file ' + path + ' deleted');
			}catch(exception) {
				//file is locked and can't be deleted, there exists a process writing data to device
				log(LOG_FILE_PATH, 'Lock file ' + path + ' can\'t be deleted');
				return false;
			}			
		}
	}
	log(LOG_FILE_PATH, 'There is no blocking operation in progress');
	return true;
}

if(WScript.Arguments.length != 2 || !checkIfNoWriteOperationInProgessExists(WScript.Arguments.Item(0), WScript.Arguments.Item(1))) {
	WScript.quit(1);
}
