#!/bin/bash

BOOKMARKS="$HOME/.config/gtk-3.0/bookmarks"
mkdir -p "$(dirname "$BOOKMARKS")"
touch "$BOOKMARKS"

# Reads the file and keeps only the lines that point 
# to existing folders, avoiding duplicates
tmp_bookmarks=$(mktemp)
while read -r line; do
    # If the line does NOT start with file:// (e.g. nfs://, smb://), we keep it as is
    if [[ ! "$line" =~ ^file:// ]]; then
        grep -qxF "$line" "$tmp_bookmarks" || echo "$line" >> "$tmp_bookmarks"
        continue
    fi

    # If it starts with file://, then we check if the local folder exists
    uri=$(echo "$line" | awk '{print $1}' | sed 's|file://||')
    if [ -d "$uri" ]; then        
        grep -qxF "$line" "$tmp_bookmarks" || echo "$line" >> "$tmp_bookmarks"
    fi
done < "$BOOKMARKS"

# Restore standard folders
REVERSE_STD=("DOWNLOAD" "VIDEOS" "PICTURES" "MUSIC" "DOCUMENTS")
for dir in "${REVERSE_STD[@]}"; do
    actual_path=$(xdg-user-dir "$dir")
    if [ -d "$actual_path" ]; then
        uri="file://$actual_path"
        # If it's not already in your bookmarks, we'll add it to the top.
        grep -q "file://$actual_path" "$tmp_bookmarks" || sed -i "1i $uri" "$tmp_bookmarks"
    fi
done

# Class link integration (00-Comune, etc.)
CLASS_DIR=$(dirname "$HOME")
for link in "$HOME"/*; do
    if [ -L "$link" ]; then
        target=$(realpath "$link")
        # If it points to a class resource but it is not your home
        if [[ "$target" == "$CLASS_DIR"/* ]] && [[ "$target" != "$HOME"* ]]; then    
            LABEL=$(basename "$link")
            NEW_LINE="file://$link $LABEL"
            # Clean up any old versions of the link
            sed -i "/ $LABEL$/d" "$tmp_bookmarks"
            echo "$NEW_LINE" >> "$tmp_bookmarks"
        fi
    fi
done

# Overwrite the original file only at the end
mv "$tmp_bookmarks" "$BOOKMARKS"

