#!/bin/sh
# Portable POSIX /bin/sh — works on bash, dash, busybox ash (OpenWrt).
set -eu

if [ $# -ne 1 ]; then
    echo "Usage: bak_cp <file_path>"
    exit 1
fi

SRC="$1"

if [ ! -f "$SRC" ]; then
    echo "Error: file not found: $SRC"
    exit 1
fi

ABS_DIR="$(cd "$(dirname "$SRC")" && pwd)"
FILENAME="$(basename "$SRC")"
BACKUP_DIR="${ABS_DIR}/backup"
TARGET="${ABS_DIR}/${FILENAME}"

[ -d "$BACKUP_DIR" ] || mkdir -p "$BACKUP_DIR"

# mtime extraction with chain failover across GNU/busybox/BSD.
get_mtime_fmt() {
    f="$1"
    fmt='+%Y%m%d-%H%M%S'

    # Linux GNU / busybox: stat -c %Y → date -d @N
    if mt=$(stat -c '%Y' "$f" 2>/dev/null) && [ -n "$mt" ]; then
        if r=$(date -d "@$mt" "$fmt" 2>/dev/null) && [ -n "$r" ]; then
            printf '%s' "$r"; return 0
        fi
        # busybox without "-d @" support → try BSD-style "-r SECONDS"
        if r=$(date -r "$mt" "$fmt" 2>/dev/null) && [ -n "$r" ]; then
            printf '%s' "$r"; return 0
        fi
    fi

    # GNU/busybox shortcut: date -r FILE
    if r=$(date -r "$f" "$fmt" 2>/dev/null) && [ -n "$r" ]; then
        # BSD date misinterprets non-numeric -r arg as 0 → reject epoch-era output.
        case "$r" in
            1969*|1970*) ;;
            *) printf '%s' "$r"; return 0 ;;
        esac
    fi

    # macOS BSD: stat -f %m → date -r SECONDS
    if mt=$(stat -f '%m' "$f" 2>/dev/null) && [ -n "$mt" ]; then
        if r=$(date -r "$mt" "$fmt" 2>/dev/null) && [ -n "$r" ]; then
            printf '%s' "$r"; return 0
        fi
    fi

    return 1
}

if ! MTIME_FMT="$(get_mtime_fmt "$TARGET")"; then
    echo "Error: failed to read mtime of $TARGET"
    exit 1
fi

if [ ! -f "${BACKUP_DIR}/${FILENAME}.original" ]; then
    cp -p "$TARGET" "${BACKUP_DIR}/${FILENAME}.original"
    chmod a-wx "${BACKUP_DIR}/${FILENAME}.original"
fi

cp -p "$TARGET" "${BACKUP_DIR}/${FILENAME}.bak.${MTIME_FMT}"
chmod a-wx "${BACKUP_DIR}/${FILENAME}.bak.${MTIME_FMT}"

echo "[OK] ${BACKUP_DIR}/${FILENAME}.bak.${MTIME_FMT}"