// SPDX-License-Identifier: Unlicense

#include "backup.h"

#include "file.h"
#include "global.h"

void Backup::init()
{
  if (Settings::applicationBackupMode != BackupMode::onceOnStart)
    return;

  const tm* tm = localtime(&Global::startupTimestamp);

  char8_t subdir[18];
  sprintf(reinterpret_cast<char*>(subdir), "%4d-%02d-%02d_%02d-%02d/", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min);

  const std::u8string subdirPath = Settings::pathBackup + subdir;
  File::createDirectories(subdirPath.c_str());
  
  if (File::exists(Global::pathSettingsIni.c_str()))
  {
    const std::u8string dest = subdirPath + File::filename(Global::pathSettingsIni.c_str());
    File::copy(Global::pathSettingsIni.c_str(), dest.c_str());
  }
  if (File::exists(Settings::pathTonesIni.c_str()))
  {
    const std::u8string dest = subdirPath + File::filename(Settings::pathTonesIni.c_str());
    File::copy(Settings::pathTonesIni.c_str(), dest.c_str());
  }
  if (File::exists(Settings::pathStatsIni.c_str()))
  {
    const std::u8string dest = subdirPath + File::filename(Settings::pathStatsIni.c_str());
    File::copy(Settings::pathStatsIni.c_str(), dest.c_str());
  }
}
