#!/bin/bash

# Maintainer: EndeavourOS-Team <info at endeavouros.com>

# Ex-Maintainer:  Nissar Chababy <funilrys at outlook dot com>
# Ex-Maintainer:  Jeroen Bollen <jbinero at gmail dot comau>

pkgname=ckbcomp
pkgver=1.228
pkgrel=1
pkgdesc="Compile a XKB keyboard description to a keymap suitable for loadkeys or kbdcontrol"
arch=(any)
license=('GPL2')
depends=('perl')
sha512sums=('0fe1c80d7eef65880a1e3e74f792b2806183ebca3d569db9745f76b5ac213f3f23424237957429f3fb1c1dfb255424544d8c0d996b91fa7e912bca8df9f7f5c3')

_DIENOW() {
    echo "${FUNCNAME[1]}: $pkgname: error: $1" >&2
    exit 1
}

_ckbcomp_preparations() {
    # Fetch 'ckbcomp' from the latest sources.
    # Out: url, pkgver, source
    # Notes:
    # - salsa.debian.org seems slower...
    # - pkgver may include only numbers, lowercase letters, and "." "+" "~"

    local changed=no
    local url_pkgname="https://salsa.debian.org/installer-team/console-setup/raw/master/Keyboard/$pkgname"    # for fetching the $pkgname
    local url_pkgver="https://sources.debian.org/src/console-setup"                                           # for finding the new $pkgver
    local tmpfile=$(mktemp)                                                                                   # for saving the (new) $pkgname
    local INFO

    url="$url_pkgver"

    curl --fail -Lsm 30 -o$tmpfile "$url_pkgname" || exit 1
    if [ -x /bin/$pkgname ] ; then
        diff $tmpfile /bin/$pkgname >/dev/null || changed=yes        # If $pkgname is installed, check if there are changes.
    fi
    rm -f $tmpfile
    if [ $changed = yes ] ; then
        # $pkgname has been changed, so get the new pkgver.
        # Note: sha512sums for the new $pkgname must be changed manually.
        INFO=$(curl --fail -Lsm 30 "$url_pkgver") || _DIENOW "fetching version info failed"
        pkgver="$(echo "$INFO" | grep -wm1 'version ' | sed -E 's|.*/>([^<]+).*|\1|')"
        [ "${pkgver//[a-z0-9.+~]/}" ] && _DIENOW "sorry, pkgver ($pkgver) is invalid"
    fi
    source=("$url_pkgname")
}

_ckbcomp_preparations
unset -f _ckbcomp_preparations
unset -f _DIENOW

package() {
    install -Dm755 $pkgname   "${pkgdir}/usr/bin/$pkgname"
    rm -f ../$pkgname   # cleanup
}
