#!/bin/bash

COLOR_RESET="\e[0m"
COLOR_GREEN="\e[32m"
COLOR_YELLOW="\e[33m"

declare -A versions_by_package

while read -r repo name ver; do
    key="$name"
    versions_by_package["$key"]+="$repo:$ver "
done < <(expac --sync --listdelim=$'\n' "%r %n %v")

for pkg in "${!versions_by_package[@]}"; do
    entries=(${versions_by_package["$pkg"]})

    if [[ ${#entries[@]} -gt 1 ]]; then
        versions=()
        for entry in "${entries[@]}"; do
            versions+=("${entry#*:}")
        done

        first_version="${versions[0]}"
        all_equal=true
        for ver in "${versions[@]}"; do
            if [[ "$ver" != "$first_version" ]]; then
                all_equal=false
                break
            fi
        done

        if $all_equal; then
            printf "${COLOR_YELLOW}%-30s" "$pkg"
        else
            printf "${COLOR_GREEN}%-30s" "$pkg"
        fi

        for entry in "${entries[@]}"; do
            repo="${entry%%:*}"
            ver="${entry#*:}"
            printf "  %-15s %s" "$repo:" "$ver"
        done

        printf "${COLOR_RESET}\n"
    fi
done

