#!/bin/bash

# Check if a directory was provided as an argument
if [ -z "$1" ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

# Directory to search
SEARCH_DIR=$1
OUTPUT_FILE=".symlink_info.json"
TEMP_FILE="temp_symlinks.txt"

# Initialize temporary file
> $TEMP_FILE

# Find symlinks and their targets
find "$SEARCH_DIR" -type l | while read -r symlink; do
    target=$(readlink "$symlink")
    symlink_name=$(basename "$symlink")
    # Remove "qa/" prefix if present
    target=${target#qa/}
    echo "    \"${symlink_name}\": \"${target}\"," >> $TEMP_FILE
done

# Sort the entries
sort $TEMP_FILE > sorted_symlinks.txt

# Initialize JSON output
echo "{" > $OUTPUT_FILE

# Append sorted entries to JSON output
cat sorted_symlinks.txt >> $OUTPUT_FILE

# Remove the trailing comma from the last entry and close the JSON object
sed -i '$ s/,$//' $OUTPUT_FILE
echo "}" >> $OUTPUT_FILE

# Cleanup temporary files
rm $TEMP_FILE sorted_symlinks.txt

echo "Symlink information has been written to $OUTPUT_FILE"
