// 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.
*/

#include "actions.h"
#include "helpers.h"
#include "../app.h"
#include <fstream>
#include <sstream>
#include <errno.h>

using namespace falco::app;
using namespace falco::app::actions;

falco::app::run_result falco::app::actions::print_kernel_version(const falco::app::state& s) {
#ifdef __linux__
	// We print this info only when a kernel driver is injected
	bool const is_kernel_driver_injected = s.is_modern_ebpf() || s.is_ebpf() || s.is_kmod();
	if(!is_kernel_driver_injected) {
		return run_result::ok();
	}

	std::ifstream input_file("/proc/version");
	if(!input_file.is_open()) {
		// We don't want to fail, we just need to log something
		falco_logger::log(
		        falco_logger::level::INFO,
		        "Cannot read under '/proc/version' (err_message: '" + std::string(strerror(errno)) +
		                "', err_code: " + std::to_string(errno) + "). No info provided, go on.");
		return run_result::ok();
	}

	std::stringstream buffer;
	buffer << input_file.rdbuf();
	std::string contents(buffer.str());
	falco_logger::log(falco_logger::level::INFO, "System info: " + contents);
#endif
	return run_result::ok();
}
