#!/usr/bin/bash

#symlink_dir="$HOME/workspace"
symlink_dir="$PWD"
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 workspace
for link in "$symlink_dir"/*; do
    [ -L "$link" ] || continue       # skip non-symlinks
    base=$(basename "$link")
    target=$(readlink -f "$link")    # resolve absolute target

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

    # Create wrapper script
    cat > "$wrapper" <<EOF
#!/usr/bin/bash
mkdir -p "$backup_dir"
if [ -f "$target" ]; then
    cp -a "$target" "$backup_dir/"
fi
"$link" "\$@"
EOF

    chmod +x "$wrapper"
done
