// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 The Falco Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

The following file was originally developed in the sysdig cli
project and then contributed to the falcosecurity/libs project
(https://github.com/draios/sysdig/commit/abf90f39f8e5ea6eb4276cc3f980dbd878816ecd
with the #1737 PR). At the end, given its removal from the
falcosecurity/libs project, has been reintroduced to the
draios/sysdig project.

*/

#ifndef _WIN32
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef __GLIBC__
#include <execinfo.h>
#endif
#include <unistd.h>
#include <sys/time.h>
#include <netdb.h>
#include <strings.h>
#include <sys/ioctl.h>
#include <fnmatch.h>
#include <string>
#else
#pragma comment(lib, "Ws2_32.lib")
#include <WinSock2.h>
#include "Shlwapi.h"
#pragma comment(lib, "shlwapi.lib")
#endif
#include <algorithm>
#include <functional>
#include <errno.h>

#include <libsinsp/sinsp.h>
#include <libsinsp/sinsp_int.h>
#include <libsinsp/sinsp_errno.h>
#include <libsinsp/sinsp_signal.h>
#include <libsinsp/filter.h>
#include <libsinsp/filterchecks.h>
#include <libsinsp/utils.h>
#include <chisel/chisel.h>
#include <chisel/chisel_utils.h>

#ifndef PATH_MAX
#define PATH_MAX 4096
#endif

using namespace std;

const chiseldir_info g_chisel_dirs_array[] =
	{
		{false, ""}, // file as is
#ifdef _WIN32
		{false, "c:/" CHISEL_TOOL_LIBRARY_NAME "/chisels/"},
#endif
		{false, "./chisels/"},
		{true, "~/.chisels/"},
};

vector<chiseldir_info>* g_chisel_dirs = NULL;
chisel_initializer g_chisel_initializer;

#ifndef _WIN32
static std::string realpath_ex(const std::string& path)
{
	char *home;
	char* resolved;

	if(!path.empty() && path[0]=='~' && (home = getenv("HOME")))
	{
		std::string expanded_home = home;
		expanded_home += path.c_str()+1;
		resolved = realpath(expanded_home.c_str(), nullptr);
	}
	else
	{
		resolved = realpath(path.c_str(), nullptr);
	}

	if (!resolved)
	{
		return "";
	}
	std::string ret = resolved;
	free(resolved);
	return ret;
}
#endif

//
// loading time initializations
//
chisel_initializer::chisel_initializer()
{
	//
	// Init the chisel directory list
	//
	g_chisel_dirs = NULL;
	g_chisel_dirs = new vector<chiseldir_info>();

	for(uint32_t j = 0; j < sizeof(g_chisel_dirs_array) / sizeof(g_chisel_dirs_array[0]); j++)
	{
		if(g_chisel_dirs_array[j].m_need_to_resolve)
		{
#ifndef _WIN32
			std::string resolved_path = realpath_ex(g_chisel_dirs_array[j].m_dir);
			if(!resolved_path.empty())
			{
				if(resolved_path[resolved_path.size() - 1] != '/')
				{
					resolved_path += '/';
				}

				chiseldir_info cdi;
				cdi.m_need_to_resolve = false;
				cdi.m_dir = std::move(resolved_path);
				g_chisel_dirs->push_back(cdi);
			}
#else
			g_chisel_dirs->push_back(g_chisel_dirs_array[j]);
#endif
		}
		else
		{
			g_chisel_dirs->push_back(g_chisel_dirs_array[j]);
		}
	}
}

chisel_initializer::~chisel_initializer()
{
	if(g_chisel_dirs)
	{
		delete g_chisel_dirs;
	}
}

void chisel_add_dir(string dirname, bool front_add)
{
	trim(dirname);

	if(dirname[dirname.size() -1] != '/')
	{
		dirname += "/";
	}

	chiseldir_info ncdi;

	ncdi.m_dir = std::move(dirname);
	ncdi.m_need_to_resolve = false;

	if(front_add)
	{
		g_chisel_dirs->insert(g_chisel_dirs->begin(), ncdi);
	}
	else
	{
		g_chisel_dirs->push_back(ncdi);
	}
}
