package eu.friedcutlet.yokan.services.backup import eu.friedcutlet.yokan.database.YokanDatabaseSnapshot import eu.friedcutlet.yokan.services.files.LocalFileService import eu.friedcutlet.yokan.util.nowMillis /** * Full native backups taken right before a restore, kept under * `/safety_snapshots` with a small JSON index. Only the newest * [MAX_SNAPSHOTS] are kept. */ internal class SafetySnapshotStore(private val files: LocalFileService) { private val json = BackupJson private val dir get() = "${files.backupRoot}/safety_snapshots" private val metaPath get() = "$dir/snapshots.json" fun list(): List = readMeta().filter { files.exists(it.backupPath) } fun record(snapshot: YokanDatabaseSnapshot, description: String): SafetySnapshot { val createdAt = nowMillis() val backupPath = "$dir/safety-$createdAt.json" val payload = BackupSnapshot( createdAtMillis = createdAt, sourceApp = "yokan-kmp", settings = snapshot.settings, includedSections = BackupSection.all.toList(), mangas = snapshot.mangas, chapters = snapshot.chapters, categories = snapshot.categories, sources = snapshot.sources, histories = snapshot.histories, updates = snapshot.updates, tracks = snapshot.tracks, trackPreferences = snapshot.trackPreferences, customButtons = snapshot.customButtons, changedParts = snapshot.changedParts, ) files.writeBytes(backupPath, json.encodeToString(BackupSnapshot.serializer(), payload).encodeToByteArray()) val newSnapshot = SafetySnapshot(backupPath = backupPath, createdAt = createdAt, description = description) val updated = listOf(newSnapshot) + readMeta() for (old in updated.drop(MAX_SNAPSHOTS)) { files.deleteRecursively(old.backupPath) } writeMeta(updated.take(MAX_SNAPSHOTS)) return newSnapshot } fun remove(snapshot: SafetySnapshot) { files.deleteRecursively(snapshot.backupPath) val metaBytes = files.readBytes(metaPath) if (metaBytes.isEmpty()) return val remaining = decodeMeta(metaBytes).filterNot { it.backupPath == snapshot.backupPath } if (remaining.isEmpty()) files.deleteRecursively(metaPath) else writeMeta(remaining) } fun clear() { for (s in list()) { files.deleteRecursively(s.backupPath) } files.deleteRecursively(metaPath) } private fun readMeta(): List = decodeMeta(files.readBytes(metaPath)) private fun decodeMeta(metaBytes: ByteArray): List { if (metaBytes.isEmpty()) return emptyList() return runCatching { json.decodeFromString>(metaBytes.decodeToString()) }.getOrNull().orEmpty().filter { it.backupPath.startsWith("$dir/") && it.backupPath.removePrefix("$dir/").matches(Regex("safety-[0-9]+\\.json")) } } private fun writeMeta(snapshots: List) { files.writeBytes(metaPath, json.encodeToString(snapshots).encodeToByteArray()) } private companion object { const val MAX_SNAPSHOTS = 3 } }