/*
   BAREOS® - Backup Archiving REcovery Open Sourced

   Copyright (C) 2019-2026 Bareos GmbH & Co. KG

   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version three of the GNU Affero General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.
*/
#if defined(HAVE_MINGW)
#  include "include/bareos.h"
#  include "gtest/gtest.h"
#else
#  include "gtest/gtest.h"
#  include "include/bareos.h"
#endif

#include "lib/parse_conf.h"
#include "stored/backends/generic_tape_device.h"
#include "stored/device_resource.h"
#include "stored/stored.h"
#include "stored/stored_globals.h"
#include "stored/stored_conf.h"

namespace storagedaemon {

namespace {

void ResetSdConfigGlobals()
{
  my_config = nullptr;
  me = nullptr;
  configfile = nullptr;
}

class TestTapeDevice : public generic_tape_device {
 public:
  explicit TestTapeDevice(bool immediate_supported)
      : immediate_supported_(immediate_supported)
  {
    errmsg = GetMemory(256);
    prt_name = GetMemory(32);
    PmStrcpy(errmsg, "");
    PmStrcpy(prt_name, "test-tape");
    fd = 1;
    SetAppend();
  }

  ~TestTapeDevice() override { fd = -1; }

  int d_close(int) override { return 0; }

  int d_ioctl(int, ioctl_req_t request, char* op) override
  {
    EXPECT_EQ(request, static_cast<ioctl_req_t>(MTIOCTOP));
    auto* mt_com = reinterpret_cast<mtop*>(op);
    operations.push_back(mt_com->mt_op);
#if defined(MTWEOFI)
    if (mt_com->mt_op == MTWEOFI && !immediate_supported_) {
      errno = ENOTTY;
      return -1;
    }
#endif
    return 0;
  }

  std::vector<short> operations;

 private:
  bool immediate_supported_;
};

class CountingTapeDevice : public generic_tape_device {
 public:
  CountingTapeDevice()
  {
    errmsg = GetMemory(64);
    prt_name = GetMemory(32);
    PmStrcpy(errmsg, "");
    PmStrcpy(prt_name, "counting-tape");
  }

  ~CountingTapeDevice() override { fd = -1; }

  bool weof(int num) override
  {
    normal_weof_count += num;
    return true;
  }

  bool weof_immediate(int num) override
  {
    immediate_weof_count += num;
    return true;
  }

  int d_close(int) override { return 0; }

  int normal_weof_count = 0;
  int immediate_weof_count = 0;
};

}  // namespace

TEST(ConfigParser_SD, test_stored_config)
{
  OSDependentInit();
  ResetSdConfigGlobals();

#if HAVE_WIN32
  WSA_Init();
#endif

  std::string path_to_config_file
      = std::string("configs/bareos-configparser-tests");
  my_config = InitSdConfig(path_to_config_file.c_str(), M_CONFIG_ERROR);
  ParseSdConfig(configfile, M_CONFIG_ERROR);

  my_config->DumpResources(PrintMessage, NULL);

  delete my_config;
  ResetSdConfigGlobals();
}

void test_CFG_TYPE_STR_VECTOR_OF_DIRS(StorageResource* res)
{
  EXPECT_EQ(res->backend_directories.size(), 9);
  /*  WIN32:
   *  cmake uses some value for PATH_BAREOS_BACKENDDIR,
   *  which ends up in the configuration files
   *  but this is later overwritten in the Director Daemon with ".".
   *  Therefore we skip this test. */
#if !defined(HAVE_WIN32)
  EXPECT_EQ(res->backend_directories.at(0), PATH_BAREOS_BACKENDDIR);
#endif
}

#if HAVE_DYNAMIC_SD_BACKENDS
TEST(ConfigParser_SD, CFG_TYPE_STR_VECTOR_OF_DIRS)
{
  std::string test_name = std::string(
      ::testing::UnitTest::GetInstance()->current_test_info()->name());

  OSDependentInit();
  ResetSdConfigGlobals();

#  if HAVE_WIN32
  WSA_Init();
#  endif

  InitMsg(nullptr, nullptr);

  std::string path_to_config_file
      = std::string("configs/bareos-configparser-tests/bareos-sd-") + test_name
        + std::string(".conf");
  my_config = InitSdConfig(path_to_config_file.c_str(), M_ERROR_TERM);
  ASSERT_TRUE(my_config->ParseConfig());

  my_config->DumpResources(PrintMessage, NULL);

  std::string sd_resource_name = "bareos-sd";

  StorageResource* my_res
      = static_cast<StorageResource*>(my_config->GetNextRes(R_STORAGE, NULL));
  EXPECT_EQ(sd_resource_name, my_res->resource_name_);

  test_CFG_TYPE_STR_VECTOR_OF_DIRS(my_res);

  TermMsg();

  delete my_config;
  ResetSdConfigGlobals();
}
#endif

TEST(ConfigParser_SD, maximum_file_size_non_flushing_filemark_defaults_to_true)
{
  DeviceResource resource;
  EXPECT_TRUE(resource.max_file_size_nonflushing_filemark);

  resource.max_file_size_nonflushing_filemark = false;
  DeviceResource copied(resource);
  EXPECT_FALSE(copied.max_file_size_nonflushing_filemark);

  DeviceResource assigned;
  assigned = resource;
  EXPECT_FALSE(assigned.max_file_size_nonflushing_filemark);
}

TEST(ConfigParser_SD, maximum_file_size_non_flushing_filemark_is_parsed)
{
  OSDependentInit();
  ResetSdConfigGlobals();

#if HAVE_WIN32
  WSA_Init();
#endif

  std::string path_to_config_file
      = std::string("configs/bareos-configparser-tests");
  my_config = InitSdConfig(path_to_config_file.c_str(), M_CONFIG_ERROR);
  ASSERT_TRUE(my_config->ParseConfig());

  auto* default_resource = static_cast<DeviceResource*>(
      my_config->GetResWithName(R_DEVICE, "FileStorage"));
  ASSERT_NE(default_resource, nullptr);
  EXPECT_TRUE(default_resource->max_file_size_nonflushing_filemark);

  auto* disabled_resource = static_cast<DeviceResource*>(
      my_config->GetResWithName(R_DEVICE, "FileStorageNonFlushingDisabled"));
  ASSERT_NE(disabled_resource, nullptr);
  EXPECT_FALSE(disabled_resource->max_file_size_nonflushing_filemark);

  delete my_config;
  ResetSdConfigGlobals();
}

TEST(ConfigParser_SD, immediate_filemark_uses_immediate_ioctl_or_falls_back)
{
  TestTapeDevice dev{/*immediate_supported=*/false};

  ASSERT_TRUE(dev.weof_immediate(1));

#if defined(MTWEOFI)
  ASSERT_EQ(dev.operations.size(), 2U);
  EXPECT_EQ(dev.operations[0], MTWEOFI);
  EXPECT_EQ(dev.operations[1], MTWEOF);
#else
  ASSERT_EQ(dev.operations.size(), 1U);
  EXPECT_EQ(dev.operations[0], MTWEOF);
#endif
  EXPECT_EQ(dev.GetFile(), 1U);
  EXPECT_EQ(dev.GetBlockNum(), 0U);
}

TEST(ConfigParser_SD, immediate_filemark_uses_immediate_ioctl_when_supported)
{
  TestTapeDevice dev{/*immediate_supported=*/true};

  ASSERT_TRUE(dev.weof_immediate(2));

#if defined(MTWEOFI)
  ASSERT_EQ(dev.operations.size(), 1U);
  EXPECT_EQ(dev.operations[0], MTWEOFI);
#else
  ASSERT_EQ(dev.operations.size(), 1U);
  EXPECT_EQ(dev.operations[0], MTWEOF);
#endif
  EXPECT_EQ(dev.GetFile(), 2U);
  EXPECT_EQ(dev.GetBlockNum(), 0U);
}

TEST(ConfigParser_SD, tape_flush_issues_mtnop)
{
  TestTapeDevice dev{/*immediate_supported=*/true};

  ASSERT_TRUE(dev.d_flush(nullptr));
  ASSERT_EQ(dev.operations.size(), 1U);
  EXPECT_EQ(dev.operations[0], MTNOP);
}

TEST(ConfigParser_SD, max_file_size_filemark_uses_immediate_path_by_default)
{
  CountingTapeDevice dev;

  ASSERT_TRUE(dev.weof_for_max_file_size(1));
  EXPECT_EQ(dev.normal_weof_count, 0);
  EXPECT_EQ(dev.immediate_weof_count, 1);
}

TEST(ConfigParser_SD, max_file_size_filemark_can_use_flushing_path)
{
  CountingTapeDevice dev;
  dev.max_file_size_nonflushing_filemark = false;

  ASSERT_TRUE(dev.weof_for_max_file_size(2));
  EXPECT_EQ(dev.normal_weof_count, 2);
  EXPECT_EQ(dev.immediate_weof_count, 0);
}

}  // namespace storagedaemon
