using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using Omegasis.SaveBackup.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
namespace Omegasis.SaveBackup
{
/// The mod entry point.
public class SaveBackup : Mod
{
/*********
** Fields
*********/
/// The folder path containing the game's app data.
private static readonly string AppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StardewValley");
/// The folder path containing the game's saves.
private static readonly string SavesPath = Path.Combine(SaveBackup.AppDataPath, "Saves");
/// The folder path containing backups of the save before the player starts playing.
private static readonly string PrePlayBackupsPath = Path.Combine(SaveBackup.AppDataPath, "Backed_Up_Saves", "Pre_Play_Saves");
/// The folder path containing nightly backups of the save.
private static readonly string NightlyBackupsPath = Path.Combine(SaveBackup.AppDataPath, "Backed_Up_Saves", "Nightly_InGame_Saves");
/// The mod configuration.
private ModConfig Config;
/*********
** Public methods
*********/
/// The mod entry point, called after the mod is first loaded.
/// Provides simplified APIs for writing mods.
public override void Entry(IModHelper helper)
{
this.Config = helper.ReadConfig();
this.BackupSaves(SaveBackup.PrePlayBackupsPath);
helper.Events.GameLoop.Saving += this.OnSaving;
}
/*********
** Private methods
*********/
/// Raised before the game begins writes data to the save file (except the initial save creation).
/// The event sender.
/// The event arguments.
private void OnSaving(object sender, SavingEventArgs e)
{
this.BackupSaves(SaveBackup.NightlyBackupsPath);
}
/// Back up saves to the specified folder.
/// The folder path in which to generate saves.
private void BackupSaves(string folderPath)
{
// back up saves
Directory.CreateDirectory(folderPath);
ZipFile.CreateFromDirectory(SaveBackup.SavesPath, Path.Combine(folderPath, $"backup-{DateTime.Now:yyyyMMdd'-'HHmmss}.zip"));
// delete old backups
new DirectoryInfo(folderPath)
.EnumerateFiles()
.OrderByDescending(f => f.CreationTime)
.Skip(this.Config.SaveCount)
.ToList()
.ForEach(file => file.Delete());
}
}
}