#!/bin/sh
set -u

if command -v code-review-graph >/dev/null 2>&1; then
    code-review-graph detect-changes --brief || true
fi

version_file="VERSION"
current_version="0.1.0"

if [ -r "$version_file" ]; then
    current_version="$(tr -d '[:space:]' < "$version_file")"
fi

if [ -t 1 ] && [ -r /dev/tty ]; then
    printf 'Version web actual: %s\n' "$current_version" > /dev/tty
    printf 'Nueva version web [Enter para mantener %s]: ' "$current_version" > /dev/tty
    IFS= read -r next_version < /dev/tty || next_version="$current_version"
elif command -v osascript >/dev/null 2>&1 && [ "$(uname -s)" = "Darwin" ]; then
    next_version="$(
        CURRENT_VERSION="$current_version" osascript <<'APPLESCRIPT'
set currentVersion to system attribute "CURRENT_VERSION"
try
    set resultDialog to display dialog "Version web actual: " & currentVersion & return & "Ingresa una nueva version o deja el valor actual." default answer currentVersion buttons {"Cancelar", "Mantener", "Actualizar"} default button "Mantener" with title "Version web"
    if button returned of resultDialog is "Cancelar" then
        error number -128
    end if
    if button returned of resultDialog is "Mantener" then
        return currentVersion
    end if
    return text returned of resultDialog
on error number -128
    error number -128
end try
APPLESCRIPT
    )" || exit 1
else
    next_version="$current_version"
fi

if [ -z "$next_version" ]; then
    next_version="$current_version"
fi

case "$next_version" in
    *[!A-Za-z0-9._+-]*)
        printf 'Version web invalida: %s\n' "$next_version" >&2
        printf 'Usa solo letras, numeros, punto, guion, underscore o +.\n' >&2
        exit 1
        ;;
esac

if [ "$next_version" != "$current_version" ]; then
    printf '%s\n' "$next_version" > "$version_file"
    git add "$version_file"
    printf 'Version web actualizada a %s y agregada al commit.\n' "$next_version" >&2
fi
