#!/usr/bin/bash

symlink_dir="$PWD"       # current directory
backup_dir="$HOME/BACKUP_OF_LINKED_FILES"
suffix="_run"            # tag to append to wrapper script names

mkdir -p "$backup_dir"

# Loop through all symlinks in the current directory
for link in "$symlink_dir"/*; do
    [ -L "$link" ] || continue        # skip non-symlinks
    target=$(readlink -f "$link")     # resolve absolute target
    [ -f "$target" ] || continue      # skip symlinks to directories
    base=$(basename "$link")

    wrapper="$symlink_dir/${base}${suffix}"

    # Create wrapper script
    cat > "$wrapper" <<EOF
#!/usr/bin/bash
mkdir -p "$backup_dir"
cp -a "$target" "$backup_dir/"
"$link" "\$@"
EOF

    chmod +x "$wrapper"
done

# timestamped backup (change if you prefer non-timestamped)
#cp -a "\$target" "\$backup_dir/${base}_\$(
#    printf '%s' "$ts"
#)"
