# Maintainer (aur): Andrea Feletto <andrea at andreafeletto.com>
# Maintainer: Wael Karram <wael at waelk.tech>
# Contributor: bill-auger <bill-auger at programmer.net>


# parabola changes and rationale:
# - delete unlicensed files
# - add openrc service files
# - add support for armv7h and i686
# - pin to strongly-coupled dependency versions


pkgname=gmid
pkgver=2.0.2
pkgrel=1
pkgdesc='Fast Gemini server written with security in mind.'
arch=('x86_64')
arch+=('i686' 'armv7h')
url='https://gmid.omarpolo.com'
license=('custom:ISC')
install=${pkgname}.install
backup=(etc/conf.d/${pkgname}
        etc/${pkgname}.conf)
depends=('libretls' 'libbsd')
source=(
	"https://ftp.omarpolo.com/$pkgname-$pkgver.tar.gz"
	#"gmid.service" # parabola mksource over-ride
	#"gmid.conf"    # parabola mksource over-ride
)
sha256sums=(
	'61baf50d3d1c86d4ce4fceea9e422a336db4259b76052bbc8eec1d47abb417c9'
	# parabola mksource over-ride
	# parabola mksource over-ride
)


# parabola mksource over-rides
mksource=(     ${source[*]}     )
mksha256sums=( ${sha256sums[*]} )
source=(https://repo.parabola.nu/other/${pkgname}-libre/${pkgname}-${pkgver}.parabola.tar.gz{,.sig}
        gmid.service
        gmid.sysusers
        gmid.confd
        gmid.initd
        gmid.conf
        index.gmi)
sha256sums=('d911214d0d4a75f0c9140d892afb3d2dac02c24f3e78cfdb60409afa0c155d3b'
            'SKIP'
            '946de0766343225068a0e3f38cb39a4a93ef312525dd775226b938cd08706b94'
            '4d943727a57dbf5f246963c0f90ccc54919cc2296538457e6b16f29f7580d9d6'
            'eddbe93741d01077426bc0239db42815c75a0da5191b4e6528df60ae3e0e5bb3'
            'f396c7db961c45ddb8e48acf42708b3faf9df2a3eaa56f30d9e64d4de0971e88'
            '7acf491fee5f2693b30666b1f2c6eb0a4db33e9ef3154e1cbfb62186c6fa7be6'
            '361cd4ef2b47437b0f5729d56d0ef88851e56812ab88546c82cda0092fe86139')
validpgpkeys=('3954A7AB837D0EA9CFA9798925DB7D9B5A8D4B40') # bill-auger


# NOTE: The files removed in mksource() are not always present.
#       They tend to disappear and re-appear.
_MKSOURCE_ERR_FMT="ERROR: %s - mksource() was not applied or needs re-working - sources may contain non-free files"
_NONFREE_FILES=( contrib )
_PREV_NONFREE_FILES=( site )


_version_constraint() # (dep_pkgname [precision])
{
  Log() { [[ "${FUNCNAME[2]}" == package ]] && echo "$@" >&2 || : ; }


  local dep_pkgname=$1
  declare -i req_precision=$2
  local full_version=$(pacman -S --print-format='%v' ${dep_pkgname} 2> /dev/null | tail -n 1)
  local n_dots=$(tmp=${full_version%-*} ; tmp=${tmp//[^\.]} ; echo "${#tmp}" ;)
  local def_precision=$(( n_dots + 1 ))
  local is_prec_valid=$(( req_precision > 0 && req_precision <= def_precision ))
  local precision=$((( is_prec_valid )) && echo ${req_precision} || echo ${def_precision})
  local pkgver_rx='[0-9A-Za-z_]+'
  pkgver_rx=$(sed 's|\]|\+]|' <<<${pkgver_rx}) # according to the wiki, '+' is not allowed,
                                               # but some pkgver have it (eg: 5.15.10+kde+r130)
  local subver_rx='\.'${pkgver_rx}
  local pkgrel_rx='[0-9]+'
  local garbage_rx='[^0-9].*'
  local capture_rx=${pkgver_rx}
  for (( n_dots=1 ; n_dots < precision ; ++n_dots )) ; do capture_rx+=${subver_rx} ; done ;
  local version pkgrel has_dot_char version_min version_max constraint_string
  declare -i subver subver_inc pkgrel_inc

  if   [[ "${full_version}" =~ ^(${capture_rx})(${subver_rx})*-(${pkgrel_rx}).*$ ]]
  then version=${BASH_REMATCH[1]} # pkgver cut to the requested precision
       #unused=${BASH_REMATCH[2]} # discarded pkgver segments
       pkgrel=${BASH_REMATCH[3]}  # pkgrel with non-numerics right-trimmed
       has_dot_char=$([[ "${version}" =~ \. ]] ; echo $(( ! $? )) ; )
       subver=$(sed "s|${garbage_rx}||" <<<${version##*.}) # right-trim from any non-numeric
       version=$( (( has_dot_char )) && echo ${version%.*}.${subver} || echo ${subver} )
       subver_inc=$(( subver + 1 ))
       pkgrel_inc=$(( pkgrel + 1 ))
       version_min=$(   (( ! is_prec_valid    )) && echo ${full_version%-*}-${pkgrel} || \
                                                    echo ${version}                      )
       version_max=$( ( (( ! is_prec_valid    )) && echo ${full_version%-*}-${pkgrel_inc} ) || \
                      ( [[ "${version}" =~ \. ]] && echo ${version%.*}.${subver_inc}      ) || \
                                                    echo ${subver_inc}                         )
       constraint_string="${dep_pkgname}>=${version_min} ${dep_pkgname}<${version_max}"

       Log "Applied version constraint: '${constraint_string}'"
  else Log "ERROR: in _version_constraint() parsing: dep_pkgname='${dep_pkgname}' full_version='${full_version}'"
       exit 1
  fi

  unset -f Log

  echo -n "${constraint_string}"
}


mksource() {
	cd "$srcdir/$pkgname-$pkgver"

	# Remove unlicensed files
	local nonfree_file
	local err_msgs=()
	for nonfree_file in "${_NONFREE_FILES[@]}"
	do
		if [[ ! -e ${nonfree_file} ]]
		then
			err_msgs+=( "nonfree_file: '${nonfree_file}' does not exist" )
		elif ! rm -r ${nonfree_file}
		then
			err_msgs+=( "cannot delete nonfree_file: '${nonfree_file}'" )
		fi
	done
	for nonfree_file in "${_PREV_NONFREE_FILES[@]}"
	do
		if [[ -e ${nonfree_file} ]]
		then
			err_msgs+=( "previous nonfree_file: '${nonfree_file}' re-appeared" )
		fi
	done

	# display error report
	if (( ${#err_msgs} ))
	then printf "${_MKSOURCE_ERR_FMT}" "${err_msgs[@]}"
		return 1
	fi
}

prepare() {
	cd "$srcdir/$pkgname-$pkgver"

	# verify mksource treatment
	local nonfree_file
	local err_msgs=()
	for nonfree_file in "${_NONFREE_FILES[@]}"
	do
		if [[ -d ${nonfree_file} ]]
		then
			err_msgs+=( "nonfree_file: '${nonfree_file}' found - deleting" )
			rm -rf ${nonfree_file}
		fi
	done

	# display error report
	if (( ${#err_msgs} ))
	then
		printf "${_MKSOURCE_ERR_FMT/ERROR:\ /WARNING:\ }" "${err_msgs[@]}"
	fi
}

build() {
	cd "$srcdir/$pkgname-$pkgver"

	MANDIR='usr/share/man/' ./configure --prefix='usr/'
	make
}

package() {
	# pin to strongly-coupled dependency versions
	depends=( ${depends[*]/libretls/} $(_version_constraint libretls 3) )

	cd "$srcdir"

	# Install the config and service files.
	install -Dm644 gmid.service -t "$pkgdir/usr/lib/systemd/system"
	install -Dm644 gmid.sysusers -t "$pkgdir/usr/lib/sysusers.d"
	install -Dm644 gmid.confd "$pkgdir/etc/conf.d/gmid"
	install -Dm755 gmid.initd "$pkgdir/etc/init.d/gmid"
	install -Dm644 gmid.conf "$pkgdir/etc/gmid.conf"

	# Install the program files.
	cd "$srcdir/$pkgname-$pkgver"
	make DESTDIR="$pkgdir/" install

	# Install the documentation files.
	install -Dm644 LICENSE -t "$pkgdir/usr/share/licenses/$pkgname"
	install -Dm644 README.md -t "$pkgdir/usr/share/doc/$pkgname"
	install -Dm644 ../index.gmi "$pkgdir/usr/share/doc/$pkgname/index.gmi"
}
