#! /usr/bin/env nix-shell
#! nix-shell -i bash -p bash zenity firefox

# Path to the list file
LIST_PATH="/srv/server/jawz/.config/jawz/lists/jawz/watch.txt"
KEPT_LINKS_PATH="/srv/server/jawz/.config/jawz/lists/jawz/kept_links.txt"

# Check if the list file exists
if [[ ! -f $LIST_PATH ]]; then
    echo "List file not found at $LIST_PATH!"
    exit 1
fi

touch $KEPT_LINKS_PATH

# Function to open a link in Firefox
open_link() {
    local link=$1
    firefox --new-tab "$link" &
}

# Function to show Zenity prompt
prompt_user() {
    local link=$1
    zenity --question --text="Do you want to keep this link?\n$link" --title="Keep Link?"
}

# Main loop
while [[ -s $LIST_PATH ]]; do
    # Select a random link from the list file
    link=$(grep -v -e "wikifeet.com" -e "kemono.su" -e "kemono.party" "$LIST_PATH" |
        grep -vxFf "$KEPT_LINKS_PATH" | shuf -n 1)

    # If no link is found, exit the loop
    if [[ -z $link ]]; then
        echo "No more links to process or only excluded/kept links remain."
        break
    fi

    # Open the link in Firefox
    open_link "$link"

    # Wait for a short time to allow Firefox to open the link
    sleep 3

    # Show Zenity prompt to the user
    if prompt_user "$link"; then
        # If the user wants to keep the link, add it to the kept links file
        echo "$link" >>"$KEPT_LINKS_PATH"
        echo "Link kept: $link"
    else
        # If the user does not want to keep the link, remove it from the list file
        grep -vF "$link" "$LIST_PATH" >temp.txt && mv temp.txt "$LIST_PATH"
        echo "Link removed: $link"
    fi

done

echo "No more links in $LIST_PATH"
