/**
 * Copyright (c) 2014-present, The osquery authors
 *
 * This source code is licensed as defined by the LICENSE file found in the
 * root directory of this source tree.
 *
 * SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only)
 */

#include <osquery/core/flags.h>
#include <osquery/database/database.h>
#include <osquery/logger/logger.h>
#include <osquery/utils/conversions/join.h>
#include <osquery/utils/json/json.h>
#include <osquery/utils/system/time.h>

#include <osquery/carver/carver_utils.h>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

namespace osquery {

CLI_FLAG(bool,
         disable_carver,
         true,
         "Disable the osquery file carver (default true)");

std::atomic<bool> kCarverPendingCarves{true};

std::string createCarveGuid() {
  return boost::uuids::to_string(boost::uuids::random_generator()());
}

Status carvePaths(const std::set<std::string>& paths,
                  const std::string& request_id,
                  std::string& carve_guid) {
  carve_guid = createCarveGuid();

  JSON tree;
  tree.addCopy("carve_guid", carve_guid);
  tree.addCopy("time", getUnixTime());
  tree.addCopy("status", kCarverStatusScheduled);
  tree.addCopy("sha256", "");
  tree.addCopy("size", -1);
  tree.addCopy("request_id", request_id);

  if (paths.size() > 1) {
    tree.addCopy("path", osquery::join(paths, ","));
  } else {
    tree.addCopy("path", *(paths.begin()));
  }

  std::string out;
  auto s = tree.toString(out);
  if (!s.ok()) {
    VLOG(1) << "Failed to serialize carve paths: " << s.what();
    return s;
  }

  kCarverPendingCarves = true;
  return setDatabaseValue(kCarves, kCarverDBPrefix + carve_guid, out);
}
} // namespace osquery
