skuka

ai-written script vs my script

so a while back i asked claude to write a python script which would backup a .kdbx file to a local nas server. i have not kept the copy of it, but i have asked it again and here is what it wrote (very similar to what i had):

#!/usr/bin/env python3
"""
kdbx_backup.py - Safely back up a KeePass (.kdbx) database to a NAS.

Features
  * Validates the source really is a KDBX file (magic bytes).
  * Waits until the file is stable (not mid-save by KeePass/KeePassXC).
  * Skips the copy if the latest backup is identical (SHA-256).
  * Atomic copy: writes to a temp file, fsyncs, verifies hash, then renames.
  * Timestamped versions + a "latest" copy; old versions pruned (--keep).
  * Works with any mounted path: SMB/NFS mount, /Volumes/NAS, \\\\NAS\\share, Z:\\
  * Standard library only. Exit codes: 0 ok/skipped, 1 error, 2 NAS unreachable.

Usage
  python3 kdbx_backup.py                      # uses defaults below
  python3 kdbx_backup.py -s ~/sp.kdbx -d /mnt/nas/backup/keepass --keep 50
  python3 kdbx_backup.py --dry-run -v

Schedule
  Linux/macOS (crontab -e), hourly:
    0 * * * * /usr/bin/python3 /path/kdbx_backup.py --log ~/kdbx_backup.log
  Windows Task Scheduler action:
    pythonw.exe C:\\path\\kdbx_backup.py -s C:\\Users\\me\\sp.kdbx -d \\\\NAS\\backup\\keepass
"""

from __future__ import annotations

import argparse
import hashlib
import logging
import os
import shutil
import sys
import time
from datetime import datetime
from pathlib import Path

# ---- Defaults (edit these or override via CLI / env vars) -------------------
DEFAULT_SOURCE = os.environ.get("KDBX_SOURCE", "~/sp.kdbx")
DEFAULT_DEST = os.environ.get("KDBX_DEST", "/mnt/nas/backup/keepass")
DEFAULT_KEEP = int(os.environ.get("KDBX_KEEP", "30"))
# -----------------------------------------------------------------------------

KDBX_SIG1 = b"\x03\xd9\xa2\x9a"  # 0x9AA2D903 little-endian
KDBX_SIG2 = b"\x67\xfb\x4b\xb5"  # 0xB54BFB67 little-endian
TS_FMT = "%Y%m%d-%H%M%S"
CHUNK = 1024 * 1024

log = logging.getLogger("kdbx_backup")


class BackupError(Exception):
    pass


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for block in iter(lambda: f.read(CHUNK), b""):
            h.update(block)
    return h.hexdigest()


def validate_kdbx(path: Path) -> None:
    if not path.is_file():
        raise BackupError(f"Source not found: {path}")
    with path.open("rb") as f:
        header = f.read(8)
    if header[:4] != KDBX_SIG1 or header[4:8] != KDBX_SIG2:
        raise BackupError(f"Not a valid KDBX file (bad signature): {path}")


def wait_until_stable(path: Path, interval: float = 2.0, attempts: int = 10) -> None:
    """Ensure size+mtime don't change between two checks (file not being written)."""
    prev = None
    for _ in range(attempts):
        st = path.stat()
        cur = (st.st_size, st.st_mtime_ns)
        if cur == prev:
            return
        prev = cur
        time.sleep(interval)
    raise BackupError("Source file keeps changing; is KeePass saving? Try again later.")


def check_dest(dest: Path, create: bool) -> None:
    if not dest.exists():
        # Refuse to create a dir on the local disk when the NAS isn't mounted.
        parent = dest.parent
        if create and parent.exists() and os.access(parent, os.W_OK):
            dest.mkdir(parents=True, exist_ok=True)
            log.info("Created destination folder %s", dest)
        else:
            raise FileNotFoundError(f"NAS destination not reachable: {dest}")
    if not os.access(dest, os.W_OK):
        raise PermissionError(f"Destination not writable: {dest}")


def list_versions(dest: Path, stem: str, suffix: str) -> list[Path]:
    """Timestamped versions, newest first."""
    out = []
    for p in dest.glob(f"{stem}_*{suffix}"):
        ts = p.name[len(stem) + 1 : -len(suffix)]
        try:
            datetime.strptime(ts, TS_FMT)
            out.append(p)
        except ValueError:
            continue
    return sorted(out, key=lambda p: p.name, reverse=True)


def atomic_copy(src: Path, final: Path, expected_hash: str) -> None:
    tmp = final.with_name(f".{final.name}.tmp")
    try:
        with src.open("rb") as fi, tmp.open("wb") as fo:
            shutil.copyfileobj(fi, fo, CHUNK)
            fo.flush()
            os.fsync(fo.fileno())
        shutil.copystat(src, tmp)
        got = sha256(tmp)
        if got != expected_hash:
            raise BackupError(f"Verification failed for {final.name} (hash mismatch)")
        os.replace(tmp, final)
    finally:
        if tmp.exists():
            tmp.unlink(missing_ok=True)


def prune(versions: list[Path], keep: int, dry_run: bool) -> None:
    for old in versions[keep:]:
        log.info("%sPruning old backup %s", "[dry-run] " if dry_run else "", old.name)
        if not dry_run:
            old.unlink(missing_ok=True)


def run(args: argparse.Namespace) -> int:
    src = Path(args.source).expanduser().resolve()
    dest = Path(args.dest).expanduser()
    stem, suffix = src.stem, src.suffix or ".kdbx"

    validate_kdbx(src)
    wait_until_stable(src, interval=args.stable_wait)
    check_dest(dest, create=args.create_dest)

    src_hash = sha256(src)
    versions = list_versions(dest, stem, suffix)

    if versions and not args.force and sha256(versions[0]) == src_hash:
        log.info("No changes since last backup (%s); skipping.", versions[0].name)
        prune(versions, args.keep, args.dry_run)
        return 0

    stamp = datetime.now().strftime(TS_FMT)
    target = dest / f"{stem}_{stamp}{suffix}"
    latest = dest / f"{stem}{suffix}"

    if args.dry_run:
        log.info("[dry-run] Would copy %s -> %s (and update %s)", src, target, latest.name)
        return 0

    t0 = time.monotonic()
    atomic_copy(src, target, src_hash)
    atomic_copy(src, latest, src_hash)
    size_kb = src.stat().st_size / 1024
    log.info("Backed up %s -> %s (%.1f KB, %.2f s, sha256 %s…)",
             src.name, target, size_kb, time.monotonic() - t0, src_hash[:12])

    prune(list_versions(dest, stem, suffix), args.keep, dry_run=False)
    return 0


def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser(description="Back up a KeePass .kdbx file to a NAS.")
    p.add_argument("-s", "--source", default=DEFAULT_SOURCE, help="Path to .kdbx file")
    p.add_argument("-d", "--dest", default=DEFAULT_DEST, help="NAS folder (mounted path or UNC)")
    p.add_argument("-k", "--keep", type=int, default=DEFAULT_KEEP, help="Versions to keep (default %(default)s)")
    p.add_argument("--force", action="store_true", help="Back up even if unchanged")
    p.add_argument("--create-dest", action="store_true", help="Create dest folder if its parent exists")
    p.add_argument("--stable-wait", type=float, default=2.0, help="Seconds between stability checks")
    p.add_argument("--dry-run", action="store_true", help="Show what would happen")
    p.add_argument("--log", help="Also append log output to this file")
    p.add_argument("-v", "--verbose", action="store_true")
    a = p.parse_args()
    if a.keep < 1:
        p.error("--keep must be >= 1")
    return a


def setup_logging(args: argparse.Namespace) -> None:
    fmt = logging.Formatter("%(asctime)s %(levelname)-7s %(message)s", "%Y-%m-%d %H:%M:%S")
    log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
    sh = logging.StreamHandler()
    sh.setFormatter(fmt)
    log.addHandler(sh)
    if args.log:
        fh = logging.FileHandler(Path(args.log).expanduser(), encoding="utf-8")
        fh.setFormatter(fmt)
        log.addHandler(fh)


def main() -> int:
    args = parse_args()
    setup_logging(args)
    try:
        return run(args)
    except (FileNotFoundError, PermissionError) as e:
        log.error("%s", e)
        return 2
    except BackupError as e:
        log.error("%s", e)
        return 1
    except KeyboardInterrupt:
        log.warning("Interrupted.")
        return 1
    except Exception:
        log.exception("Unexpected error")
        return 1


if __name__ == "__main__":
    sys.exit(main())

i don't know what in the world possessed me to ask it to write a python script, but this is what i did. recently, i looked over my files and decided to only keep human-made code on my computer. so i re-wrote this script. you know what i ended up with?

#!bin/bash

LOG_FILE="/var/log/sync"

echo "starting mysecretfile backup at `date`" >> $LOG_FILE
scp -i ~/.ssh/nas-ssh ~/mysecretfile.kdbx myuser@nas-storage.local:/mnt/sda1/myfiles/
echo "finished pw backup at `date`" >> $LOG_FILE

i think we have a while to go before we all get replaced lol.

ps. below is its try with bash. it probably handled some complex cases, but imho this script is really difficult to maintain.

#!/usr/bin/env bash
#
# kdbx_backup.sh - Safely back up a KeePass (.kdbx) database to a NAS.
#
# Features
#   * Validates the source really is a KDBX file (magic bytes).
#   * Waits until the file is stable (not mid-save by KeePass/KeePassXC).
#   * Skips the copy if the latest backup is identical (SHA-256).
#   * Atomic copy: temp file -> sync -> verify hash -> rename.
#   * Timestamped versions + a "latest" copy; old versions pruned (-k).
#   * Refuses to run if the NAS isn't mounted (won't fill your local disk).
#   * Works on Linux and macOS. Exit codes: 0 ok/skipped, 1 error, 2 NAS unreachable.
#
# Usage
#   ./kdbx_backup.sh                                   # uses defaults below
#   ./kdbx_backup.sh -s ~/sp.kdbx -d /mnt/nas/backup/keepass -k 50
#   ./kdbx_backup.sh -n -v                             # dry run, verbose
#
# Cron (crontab -e), hourly:
#   0 * * * * /path/kdbx_backup.sh -l ~/kdbx_backup.log

set -Eeuo pipefail
umask 077   # backups of a password DB should not be world-readable

# ---- Defaults (edit, or override via env vars / flags) ----------------------
SOURCE="${KDBX_SOURCE:-$HOME/sp.kdbx}"
DEST="${KDBX_DEST:-/mnt/nas/backup/keepass}"
KEEP="${KDBX_KEEP:-30}"
STABLE_WAIT=2
# -----------------------------------------------------------------------------

FORCE=0 DRY_RUN=0 VERBOSE=0 CREATE_DEST=0 LOGFILE=""
TMP=""

usage() {
    cat <<EOF
Usage: ${0##*/} [options]
  -s FILE   Source .kdbx file        (default: $SOURCE)
  -d DIR    NAS destination folder   (default: $DEST)
  -k N      Versions to keep         (default: $KEEP)
  -f        Force backup even if unchanged
  -c        Create dest folder if its parent exists
  -w SEC    Seconds between stability checks (default: $STABLE_WAIT)
  -n        Dry run
  -l FILE   Also append log to FILE
  -v        Verbose
  -h        Help
EOF
}

log() {
    local level=$1; shift
    [[ $level == DEBUG && $VERBOSE -eq 0 ]] && return 0
    local line
    line="$(date '+%Y-%m-%d %H:%M:%S') $(printf '%-7s' "$level") $*"
    echo "$line" >&2
    [[ -n $LOGFILE ]] && echo "$line" >>"$LOGFILE"
    return 0
}

die() { local code=$1; shift; log ERROR "$*"; exit "$code"; }

cleanup() { [[ -n $TMP && -e $TMP ]] && rm -f -- "$TMP"; return 0; }
trap cleanup EXIT
trap 'log WARNING "Interrupted."; exit 1' INT TERM

# Portable helpers (GNU vs BSD/macOS)
sha256() {
    if command -v sha256sum >/dev/null; then sha256sum -- "$1" | cut -d' ' -f1
    else shasum -a 256 -- "$1" | cut -d' ' -f1; fi
}
fstat() {  # prints "size mtime"
    stat -c '%s %Y' -- "$1" 2>/dev/null || stat -f '%z %m' -- "$1"
}

validate_kdbx() {
    [[ -f $SOURCE ]] || die 1 "Source not found: $SOURCE"
    local sig
    sig=$(head -c 8 -- "$SOURCE" | od -An -tx1 | tr -d ' \n')
    [[ $sig == 03d9a29a67fb4bb5 ]] || die 1 "Not a valid KDBX file (bad signature): $SOURCE"
}

wait_until_stable() {
    local prev="" cur i
    for ((i = 0; i < 10; i++)); do
        cur=$(fstat "$SOURCE")
        [[ $cur == "$prev" ]] && return 0
        prev=$cur
        sleep "$STABLE_WAIT"
    done
    die 1 "Source file keeps changing; is KeePass saving? Try again later."
}

check_dest() {
    if [[ ! -d $DEST ]]; then
        local parent; parent=$(dirname -- "$DEST")
        if ((CREATE_DEST)) && [[ -d $parent && -w $parent ]]; then
            mkdir -p -- "$DEST" && log INFO "Created destination folder $DEST"
        else
            die 2 "NAS destination not reachable: $DEST"
        fi
    fi
    [[ -w $DEST ]] || die 2 "Destination not writable: $DEST"
}

# Newest-first list of timestamped versions (names sort chronologically)
list_versions() {
    find "$DEST" -maxdepth 1 -type f \
        -name "${STEM}_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9]${SUFFIX}" \
        -print | sort -r
}

atomic_copy() {  # $1 = final path
    local final=$1
    TMP="$(dirname -- "$final")/.$(basename -- "$final").tmp"
    cp -p -- "$SOURCE" "$TMP"
    chmod 600 -- "$TMP" 2>/dev/null || true   # some SMB mounts ignore chmod
    sync "$TMP" 2>/dev/null || sync
    [[ $(sha256 "$TMP") == "$SRC_HASH" ]] || die 1 "Verification failed for ${final##*/} (hash mismatch)"
    mv -f -- "$TMP" "$final"
    TMP=""
}

prune() {
    local i=0 f
    while IFS= read -r f; do
        [[ -z $f ]] && continue
        if ((++i > KEEP)); then
            if ((DRY_RUN)); then log INFO "[dry-run] Would prune ${f##*/}"
            else rm -f -- "$f" && log INFO "Pruned old backup ${f##*/}"; fi
        fi
    done < <(list_versions)
}

# ---- Main -------------------------------------------------------------------
while getopts ":s:d:k:fcw:nl:vh" opt; do
    case $opt in
        s) SOURCE=$OPTARG ;;
        d) DEST=$OPTARG ;;
        k) KEEP=$OPTARG ;;
        f) FORCE=1 ;;
        c) CREATE_DEST=1 ;;
        w) STABLE_WAIT=$OPTARG ;;
        n) DRY_RUN=1 ;;
        l) LOGFILE=$OPTARG ;;
        v) VERBOSE=1 ;;
        h) usage; exit 0 ;;
        :) echo "Option -$OPTARG needs a value" >&2; usage; exit 1 ;;
        *) echo "Unknown option -$OPTARG" >&2; usage; exit 1 ;;
    esac
done

[[ $KEEP =~ ^[1-9][0-9]*$ ]] || die 1 "-k must be a positive integer"
DEST=${DEST%/}
NAME=$(basename -- "$SOURCE")
SUFFIX=".${NAME##*.}"; [[ $NAME == *.* ]] || SUFFIX=".kdbx"
STEM=${NAME%"$SUFFIX"}

validate_kdbx
wait_until_stable
check_dest

SRC_HASH=$(sha256 "$SOURCE")
LATEST_VER=$(list_versions | head -n1)
log DEBUG "Source hash $SRC_HASH, latest version: ${LATEST_VER:-none}"

if [[ -n $LATEST_VER ]] && ((FORCE == 0)) && [[ $(sha256 "$LATEST_VER") == "$SRC_HASH" ]]; then
    log INFO "No changes since last backup (${LATEST_VER##*/}); skipping."
    prune
    exit 0
fi

TARGET="$DEST/${STEM}_$(date +%Y%m%d-%H%M%S)${SUFFIX}"

if ((DRY_RUN)); then
    log INFO "[dry-run] Would copy $SOURCE -> $TARGET (and update $NAME)"
    exit 0
fi

start=$SECONDS
atomic_copy "$TARGET"
atomic_copy "$DEST/$NAME"
size_kb=$(( $(fstat "$SOURCE" | cut -d' ' -f1) / 1024 ))
log INFO "Backed up $NAME -> $TARGET (${size_kb} KB, $((SECONDS - start)) s, sha256 ${SRC_HASH:0:12}…)"

prune