import os import time import shutil import hashlib from datetime import datetime from files import FILES CHECK_INTERVAL = 300 # 5 minutos # Rutas dentro del contenedor DATA_DIR = "/data" APP_DIR = os.path.join(DATA_DIR, "app") BACKUPS_ROOT = os.path.join(DATA_DIR, "backups") os.makedirs(BACKUPS_ROOT, exist_ok=True) def log(msg): ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"[{ts}] {msg}", flush=True) def sha256sum(path): h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): h.update(chunk) return h.hexdigest() def ensure_backup_dir(file_path): file_name = os.path.basename(file_path) name, _ = os.path.splitext(file_name) backup_dir = os.path.join(BACKUPS_ROOT, name) os.makedirs(backup_dir, exist_ok=True) return backup_dir def get_latest_backup(file_path): backup_dir = ensure_backup_dir(file_path) files = sorted(os.listdir(backup_dir), reverse=True) if not files: return None return os.path.join(backup_dir, files[0]) def backup_file(file_path): backup_dir = ensure_backup_dir(file_path) file_name = os.path.basename(file_path) name, ext = os.path.splitext(file_name) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") dest = os.path.join(backup_dir, f"{name}_{timestamp}{ext}") shutil.copy2(file_path, dest) log(f"[BACKUP] Copia creada: {dest}") def process_file(file_path): if not os.path.isfile(file_path): log(f"[WARN] No existe: {file_path}") return latest = get_latest_backup(file_path) if latest is None: log(f"[INIT] Primera copia de {file_path}") backup_file(file_path) return try: current_hash = sha256sum(file_path) latest_hash = sha256sum(latest) except Exception as e: log(f"[ERROR] Hash: {e}") return if current_hash != latest_hash: log(f"[CHANGE] Detectado cambio en {file_path}") backup_file(file_path) else: log(f"[OK] Sin cambios en {file_path}") def main(): log("GameWatcher iniciado") log(f"Backups en: {BACKUPS_ROOT}") while True: for f in FILES: process_file(f) time.sleep(CHECK_INTERVAL) if __name__ == "__main__": main()