#!/usr/bin/env bash

set -Eeuo pipefail

REPO="atareao/id3cli"
INSTALL_PATH="${PATH}/id3cli"
VERSION_FILE="${PATH}/.id3cli_version"

NTFY_SERVER="http://localhost:80"
NTFY_TOPIC="${TOPIC}"
NTFY_TOKEN_FILE="${PATH}/${TOKEN_FILE}"

send_notification() {
    local message="$1"
    local token

    token="$(tr -d '\r\n' < "$NTFY_TOKEN_FILE" 2>/dev/null)" || return 1
    [[ -n "$token" ]] || return 1

    curl --fail --silent --show-error \
        -X POST \
        -H "Authorization: Bearer ${token}" \
        -H "Content-Type: text/plain; charset=utf-8" \
        -d "$message" \
        --output /dev/null \
        "${NTFY_SERVER%/}/${NTFY_TOPIC}" || true
}

current="$(cat "$VERSION_FILE" 2>/dev/null || echo '')"
latest="$(curl -sf "https://api.github.com/repos/$REPO/releases/latest" \
    | grep '"tag_name"' \
    | cut -d'"' -f4)"

if [[ -z "$latest" ]]; then
    send_notification "id3cli: no s'ha pogut obtenir la versió de GitHub."
    exit 1
fi

if [[ "$current" == "$latest" ]]; then
    exit 0
fi

send_notification "id3cli: nova versió disponible ($latest). Compilant..."

if podman run --rm \
    -v /tmp:/output \
    rust:alpine \
    sh -c "apk add --no-cache git musl-dev && \
    git clone --branch $latest --depth 1 https://github.com/$REPO.git /src && \
    cd /src && \
    cargo build --release --target x86_64-unknown-linux-musl && \
    cp target/x86_64-unknown-linux-musl/release/id3cli /output/"; then

    podman rmi rust:alpine 2>/dev/null || true

    cp /tmp/id3cli "$INSTALL_PATH"
    chmod +x "$INSTALL_PATH"
    echo "$latest" > "$VERSION_FILE"

    send_notification "id3cli: actualitzat a $latest correctament."
else
    podman rmi rust:alpine 2>/dev/null || true
    send_notification "id3cli: error durant la compilació de $latest."
    exit 1
fi