#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Find the latest Medicus backup (.fbk or .zip) in the given folder. If the newest backup is a ZIP, extract the .fbk into Z:\Medicus 3\restore. Before extraction, the restore folder is fully cleared. Prints the full path to the resulting .fbk file (for batch usage). """ import re import zipfile import shutil from pathlib import Path from datetime import datetime # ======================================== # ๐Ÿ”ง CONFIGURATION # ======================================== BACKUP_DIR = Path(r"G:\OnedriveOrdinace\OneDrive\MedicusBackup") # โœ… your real backup location RESTORE_DIR = Path(r"Z:\\Medicus 3\\restore") # destination folder for .fbk RESTORE_DIR.mkdir(parents=True, exist_ok=True) # ======================================== # ๐Ÿงน 1) Clean restore folder # ======================================== print(f"๐Ÿงน Cleaning folder: {RESTORE_DIR}") for item in RESTORE_DIR.iterdir(): try: if item.is_file() or item.is_symlink(): item.unlink() elif item.is_dir(): shutil.rmtree(item) except Exception as e: print(f"โš ๏ธ Cannot delete {item}: {e}") # ======================================== # ๐Ÿ” 2) Find newest backup file # ======================================== pattern = re.compile(r"Medicus_(\d{6})_(\d{4})\.(fbk|zip)$", re.IGNORECASE) candidates = [] for f in BACKUP_DIR.iterdir(): m = pattern.match(f.name) if m: yymmdd, hhmm, ext = m.groups() ts = datetime.strptime("20" + yymmdd + hhmm, "%Y%m%d%H%M") candidates.append((ts, f)) if not candidates: raise SystemExit("โŒ No Medicus backup files found in folder!") candidates.sort(key=lambda x: x[0], reverse=True) latest_time, latest_file = candidates[0] print(f"๐Ÿ•’ Latest backup: {latest_file.name} ({latest_time})") # ======================================== # ๐Ÿ“ฆ 3) Extract or use directly # ======================================== if latest_file.suffix.lower() == ".zip": with zipfile.ZipFile(latest_file, "r") as zf: fbk_files = [n for n in zf.namelist() if n.lower().endswith(".fbk")] if not fbk_files: raise SystemExit("โŒ ZIP file does not contain any .fbk!") fbk_name = Path(fbk_files[0]).name out_path = RESTORE_DIR / fbk_name print(f"๐Ÿ“‚ Extracting {fbk_name} โ†’ {out_path}") zf.extract(fbk_files[0], RESTORE_DIR) final_fbk = out_path else: out_path = RESTORE_DIR / latest_file.name print(f"๐Ÿ“‹ Copying {latest_file} โ†’ {out_path}") shutil.copy2(latest_file, out_path) final_fbk = out_path # ======================================== # โœ… 4) Output final .fbk path for the batch file # ======================================== print(final_fbk)