#!/bin/bash

CONF="compile.conf"

if [ ! -f "$CONF" ]; then
    echo "Error: compile.conf not found at $CONF"
    exit 1
fi

github_owner_repo() {
    local url="$1"
    if [[ "$url" =~ github\.com/([^/]+)/([^/.]+) ]]; then
        echo "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}"
    fi
}

github_latest_tag() {
    local owner_repo="$1"
    local tag
    tag=$(curl -sf "https://api.github.com/repos/$owner_repo/releases/latest" \
        | grep '"tag_name"' \
        | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/' \
        | sed 's/^v//')
    if [ -z "$tag" ]; then
        tag=$(curl -sf "https://api.github.com/repos/$owner_repo/tags" \
            | grep '"name"' \
            | head -1 \
            | sed 's/.*"name": *"\([^"]*\)".*/\1/' \
            | sed 's/^v//')
    fi
    echo "$tag"
}

current_section=""
current_version=""
current_url=""

check_section() {
    [ -z "$current_section" ] && return
    [ -z "$current_url" ] && return

    local owner_repo
    owner_repo=$(github_owner_repo "$current_url")
    if [ -z "$owner_repo" ]; then
        echo "$current_section: unable to determine GitHub repo from URL"
        return
    fi

    local latest
    latest=$(github_latest_tag "$owner_repo")
    if [ -z "$latest" ]; then
        echo "$current_section: unable to fetch latest version"
        return
    fi

    if [ "$latest" = "$current_version" ]; then
        echo "$current_section: up to date ($current_version)"
    else
        echo "$current_section: update available $current_version -> $latest"
    fi
}

while IFS= read -r line; do
    if [[ "$line" =~ ^\[(.+)\]$ ]]; then
        check_section
        current_section="${BASH_REMATCH[1]}"
        current_version=""
        current_url=""
    elif [[ "$line" =~ ^version=(.+)$ ]]; then
        current_version="${BASH_REMATCH[1]}"
    elif [[ "$line" =~ ^wget=(.+)$ ]]; then
        current_url="${BASH_REMATCH[1]}"
    elif [[ "$line" =~ ^git=(.+)$ ]]; then
        current_url="${BASH_REMATCH[1]}"
    fi
done < "$CONF"

check_section
