#!/bin/bash
# update-symlinks-to-0bin.sh
# Makes all symbolic links in the 'symlinks' folder point to 0.bin
# Only direct children, no recursion into subdirectories

set -euo pipefail  # safe scripting

# Change these if needed
SYMLINKS_DIR="symlinks/v2"
TARGET_FILE="symlinks/v2/0.bin"

# Resolve to absolute paths (highly recommended for symlinks)
TARGET_ABS="$(realpath "$TARGET_FILE")"
SYMLINKS_ABS="$(realpath "$SYMLINKS_DIR")"

# Basic checks
if [[ ! -f "$TARGET_ABS" ]]; then
    echo "Error: Target file '$TARGET_FILE' does not exist or is not a regular file." >&2
    exit 1
fi

if [[ ! -d "$SYMLINKS_ABS" ]]; then
    echo "Error: Directory '$SYMLINKS_DIR' does not exist." >&2
    exit 1
fi

echo "Updating symlinks in '$SYMLINKS_DIR' to point to '$TARGET_FILE' ..."

# Process only direct children that are symlinks
find "$SYMLINKS_ABS" -maxdepth 1 -type l | while IFS= read -r link; do
    # Get the base name so we can recreate the symlink with the same name
    basename_link="$(basename "$link")"

    # Skip the symlink named 0.bin
    [[ "$basename_link" == "0.bin" ]] && continue
    
    # Remove the old symlink (ln -f would do it in one step, but we separate for clarity)
    rm "$link"
    
    # Create new symlink with the same name pointing to 0.bin
    ln -s "$TARGET_ABS" "$SYMLINKS_ABS/$basename_link"
    
    echo "  $basename_link → $TARGET_FILE"
done

echo "Done. All $(find "$SYMLINKS_ABS" -maxdepth 1 -type l | wc -l) symlinks now point to '$TARGET_FILE'."
