// This script for DDLoginMatrix removes any sixel cache directories from
// the theme directories where image files (jpg/png/etc.) may have been
// converted to sixel files for various terminal sizes.

"use strict";

var sixelCacheDirName = "sixel_cache";

var dirEntries = directory(js.startup_dir + "DDLoginMatrixThemes/*");
for (var i = 0; i < dirEntries.length; ++i)
{
	if (!file_isdir(dirEntries[i]))
		continue;

	var fullyPathedSixelCacheDirName = dirEntries[i] + sixelCacheDirName;
	if (file_isdir(fullyPathedSixelCacheDirName))
	{
		if (deleteDirRecursive(fullyPathedSixelCacheDirName))
			log(LOG_INFO, "Removed " + fullyPathedSixelCacheDirName);
	}
}

// Removes a directory and all files in it
function deleteDirRecursive(pDirName)
{
	if (!file_isdir(pDirName))
		return true;

	log(LOG_INFO, "Removing directory: " + pDirName);
	// Delete all files in pDirName, then remove the directory
	// rmfiles() was added in Synchronet 3.20
	if (typeof(rmfiles) === "function")
	{
		var tempFilenames = directory(backslash(pDirName) + "*.*");
		if (tempFilenames.length > 0)
		{
			if (!rmfiles(pDirName))
			{
				log(LOG_ERR, "Failed to remove files in directory: " + pDirName);
				return false;
			}
		}
	}
	else
	{
		var filenames = directory(pDirName + "*");
		for (var i = 0; i < filenames.length; ++i)
		{
			if (file_isdir(filenames[i]))
			{
				if (!deleteDirRecursive(filenames[i]))
					return false;
			}
			else
			{
				if (!file_remove(filenames[i]))
				{
					log(LOG_ERR, format("Failed to remove file %s in directory %s", filenames[i], pDirName));
					return false;
				}
			}
		}
	}
	var succeeded = rmdir(pDirName);
	if (!succeeded)
		log(LOG_ERR, "Failed to remove directory: " + pDirName);

	return succeeded;
}