#!/bin/bash


## configuration ##

# NOTE: test data versions are extremely brittle - these will need adjustments routinely.
#       usually, these values will be the reported failed 'actual'. - `pacman -Syu` first!

readonly OPENEXR_VER_MIN_PR_1=3
readonly OPENEXR_VER_MIN_PR_2=3.2
readonly OPENEXR_VER_MIN_PR_3=3.2.1
readonly OPENEXR_VER_MIN_FULL=3.2.1-1
readonly OPENSHADINGLANGUAGE_VER_MIN_PR_1=1
readonly OPENSHADINGLANGUAGE_VER_MIN_PR_2=1.12
readonly OPENSHADINGLANGUAGE_VER_MIN_PR_3=1.12.14
readonly OPENSHADINGLANGUAGE_VER_MIN_PR_4=1.12.14.0
readonly OPENSHADINGLANGUAGE_VER_MIN_FULL=1.12.14.0-2
readonly WEBKIT2GTK_VER_MIN_FULL=2.42.4-2
readonly QT5BASE_VER_MIN_PR_3=5.15.12
readonly QT5BASE_VER_MIN_FULL=5.15.12+kde+r147-1
readonly OPENCASCADE_VER_MIN_FULL=1:7.7.2-4

readonly RED='\033[01;31m'
readonly GREEN='\033[00;32m'
readonly AQUA='\033[00;36m'
readonly CEND='\033[00m'


## main function for PKGBUILDs ##

_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 epoch_rx='[0-9]+:'
  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 epoch version pkgrel has_dot_char version_min version_max constraint_string
  declare -i subver subver_inc pkgrel_inc

  if   [[ "${full_version}" =~ ^(${epoch_rx})*(${capture_rx})(${subver_rx})*-(${pkgrel_rx}).*$ ]]
  then epoch=${BASH_REMATCH[1]}   # optional epoch
       version=${BASH_REMATCH[2]} # pkgver cut to the requested precision
       #unused=${BASH_REMATCH[3]} # discarded pkgver segments
       pkgrel=${BASH_REMATCH[4]}  # 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} )
       version=${epoch}${version}
       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}"
}


## tests ##

VerIncrement() # (version_string)
{
  # NOTE This is not the same parsing logic as _version_constraint().
  #      It is intended to be as simple as possible, only for the mock data.
  #      Write a new test to verify anything novel or peculiar.
  local version_string=$1
  local has_pkgrel=$([[ "$1" =~ \- ]] ; echo $((! $?)) ;)
  local split_char=$((( has_pkgrel )) && echo '-' || echo '.')
  local has_split_char=$([[ "$1" =~ "${split_char}" ]] ; echo $(( ! $? )) ; )
  local unchanged_segment=${version_string%${split_char}*}
  declare -i incremented_segment=$(( ${version_string##*${split_char}} + 1 ))

  (( ! has_split_char )) || echo -n ${unchanged_segment}${split_char}
  echo ${incremented_segment}
}
readonly OPENEXR_VER_MAX_PR_1=$(            VerIncrement ${OPENEXR_VER_MIN_PR_1}            )
readonly OPENEXR_VER_MAX_PR_2=$(            VerIncrement ${OPENEXR_VER_MIN_PR_2}            )
readonly OPENEXR_VER_MAX_PR_3=$(            VerIncrement ${OPENEXR_VER_MIN_PR_3}            )
readonly OPENEXR_VER_MAX_FULL=$(            VerIncrement ${OPENEXR_VER_MIN_FULL}            )
readonly OPENSHADINGLANGUAGE_VER_MAX_PR_1=$(VerIncrement ${OPENSHADINGLANGUAGE_VER_MIN_PR_1})
readonly OPENSHADINGLANGUAGE_VER_MAX_PR_2=$(VerIncrement ${OPENSHADINGLANGUAGE_VER_MIN_PR_2})
readonly OPENSHADINGLANGUAGE_VER_MAX_PR_3=$(VerIncrement ${OPENSHADINGLANGUAGE_VER_MIN_PR_3})
readonly OPENSHADINGLANGUAGE_VER_MAX_PR_4=$(VerIncrement ${OPENSHADINGLANGUAGE_VER_MIN_PR_4})
readonly OPENSHADINGLANGUAGE_VER_MAX_FULL=$(VerIncrement ${OPENSHADINGLANGUAGE_VER_MIN_FULL})
readonly WEBKIT2GTK_VER_MAX_FULL=$(         VerIncrement ${WEBKIT2GTK_VER_MIN_FULL}         )
readonly QT5BASE_VER_MAX_PR_3=$(            VerIncrement ${QT5BASE_VER_MIN_PR_3}            )
readonly QT5BASE_VER_MAX_FULL=$(            VerIncrement ${QT5BASE_VER_MIN_FULL}            )
readonly OPENCASCADE_VER_MAX_FULL=$(        VerIncrement ${OPENCASCADE_VER_MIN_FULL}        )


TestVersionConstraint() # ("pkgname" "precision" "expected_res")
{
  local pkgname="$1"
  local precision="$2"
  local expected_res="$3"

  local actual_res="$(_version_constraint "${pkgname}" "${precision}")"

  if   [[ "${actual_res}" == "${expected_res}" ]]
  then echo -e "${GREEN}PASS <- ${pkgname}${CEND}"                                      ; return 0 ;
  else echo -e "${RED}FAIL <- ${pkgname}${CEND}"
       echo -e "${AQUA}  expected='${expected_res}'\n  actual  ='${actual_res}'${CEND}" ; return 1 ;
  fi
}

RunTests()
{
  set -e

  precision=1 ; echo -e "\n=== precision='${precision}' ===" ;
  TestVersionConstraint 'openexr'              "${precision}" "openexr>=${OPENEXR_VER_MIN_PR_1} openexr<${OPENEXR_VER_MAX_PR_1}"
  TestVersionConstraint 'openshadinglanguage'  "${precision}" "openshadinglanguage>=${OPENSHADINGLANGUAGE_VER_MIN_PR_1} openshadinglanguage<${OPENSHADINGLANGUAGE_VER_MAX_PR_1}"

  precision=2 ; echo -e "\n=== precision='${precision}' ===" ;
  TestVersionConstraint 'openexr'              "${precision}" "openexr>=${OPENEXR_VER_MIN_PR_2} openexr<${OPENEXR_VER_MAX_PR_2}"
  TestVersionConstraint 'openshadinglanguage'  "${precision}" "openshadinglanguage>=${OPENSHADINGLANGUAGE_VER_MIN_PR_2} openshadinglanguage<${OPENSHADINGLANGUAGE_VER_MAX_PR_2}"

  precision=3 ; echo -e "\n=== precision='${precision}' ===" ;
  TestVersionConstraint 'openexr'              "${precision}" "openexr>=${OPENEXR_VER_MIN_PR_3} openexr<${OPENEXR_VER_MAX_PR_3}"
  TestVersionConstraint 'openshadinglanguage'  "${precision}" "openshadinglanguage>=${OPENSHADINGLANGUAGE_VER_MIN_PR_3} openshadinglanguage<${OPENSHADINGLANGUAGE_VER_MAX_PR_3}"

  precision=4 ; echo -e "\n=== precision='${precision}' ===" ;
  TestVersionConstraint 'openexr'              "${precision}" "openexr>=${OPENEXR_VER_MIN_FULL} openexr<${OPENEXR_VER_MAX_FULL}"
  TestVersionConstraint 'openshadinglanguage'  "${precision}" "openshadinglanguage>=${OPENSHADINGLANGUAGE_VER_MIN_PR_4} openshadinglanguage<${OPENSHADINGLANGUAGE_VER_MAX_PR_4}"

  precision= ; echo -e "\n=== full precision (default) ===" ;
  TestVersionConstraint 'openexr'              "${precision}" "openexr>=${OPENEXR_VER_MIN_FULL} openexr<${OPENEXR_VER_MAX_FULL}"
  TestVersionConstraint 'openshadinglanguage'  "${precision}" "openshadinglanguage>=${OPENSHADINGLANGUAGE_VER_MIN_FULL} openshadinglanguage<${OPENSHADINGLANGUAGE_VER_MAX_FULL}"

  precision= ; echo -e "\n=== non-existent-package ===" ;
  TestVersionConstraint 'non-existent-package' "${precision}" ''

  precision= ; echo -e "\n=== specific repo ===" ;
  TestVersionConstraint 'extra/webkit2gtk'     "${precision}" "extra/webkit2gtk>=${WEBKIT2GTK_VER_MIN_FULL} extra/webkit2gtk<${WEBKIT2GTK_VER_MAX_FULL}"

  precision=3 ; echo -e "\n=== non-numeric version ===" ;
  TestVersionConstraint 'qt5-base'             "${precision}" "qt5-base>=${QT5BASE_VER_MIN_PR_3} qt5-base<${QT5BASE_VER_MAX_PR_3}"
  precision=  ; echo -e "\n=== non-numeric version - full precision (default) ===" ;
  TestVersionConstraint 'qt5-base'             "${precision}" "qt5-base>=${QT5BASE_VER_MIN_FULL} qt5-base<${QT5BASE_VER_MAX_FULL}"

  precision=  ; echo -e "\n=== version with epoch ===" ;
  TestVersionConstraint 'opencascade'          "${precision}" "opencascade>=${OPENCASCADE_VER_MIN_FULL} opencascade<${OPENCASCADE_VER_MAX_FULL}"
}


RunTests
