#!/usr/bin/env bash
set -e

# Nomarchy Update Available Script
# Checks if flake updates are available and returns info for Waybar

REPO_DIR=""
if [ -f "/etc/nixos/flake.nix" ]; then
    REPO_DIR="/etc/nixos"
elif [ -f "/etc/nomarchy/flake.nix" ]; then
    REPO_DIR="/etc/nomarchy"
fi

if [ -z "$REPO_DIR" ]; then
    echo "Nomarchy repo not found."
    exit 0
fi

# Fast-fail if offline to avoid expensive nix commands.
if ! ping -c 1 -W 2 1.1.1.1 >/dev/null 2>&1; then
    exit 0
fi

# Get the current locked revision for Nomarchy
LOCKED_REV=$(jq -r '.nodes.nomarchy.locked.rev // empty' "$REPO_DIR/flake.lock" 2>/dev/null)

if [ -z "$LOCKED_REV" ]; then
    # Could be named something else or missing, fallback to generic icon
    echo ""
    exit 0
fi

# Check if we are pinned in flake.nix
if grep -q "rev=" "$REPO_DIR/flake.nix" 2>/dev/null; then
    # We are pinned. An update implies unpinning and upgrading.
    # We can just show the icon to encourage the user to update and unpin.
    echo ""
    exit 0
fi

# Get remote latest revision
REMOTE_URL="https://git.bemagri.xyz/bernardo/Nomarchy.git"
# Fast-fail check with git ls-remote (usually takes < 1s if online)
LATEST_REV=$(git ls-remote "$REMOTE_URL" HEAD 2>/dev/null | awk '{print $1}')

if [ -z "$LATEST_REV" ]; then
    # Couldn't reach remote
    exit 0
fi

# Compare revisions
if [ "$LOCKED_REV" != "$LATEST_REV" ]; then
    echo ""
else
    # No updates available
    echo ""
fi
