#!/bin/bash

set -e

substituiere() {
  dep="$1"
  name=${dep%>=*}
  dep=${dep#${name}}
  erg="$(
    cat "$(dirname "${me}")/perlSubstitutionen" | \
      sed 's|#.*$||' | \
      grep "\s${name}\(\s\|\$\)" | \
      sed "s|^\([^:]\+\):.*\$|perl-\1|" | \
      sed "s|^:.*\$|perl|"
  )"
  [ -z "${erg}" ] && erg="perl-${name}"
  if [ "${erg}" == "perl" ] && echo "${dep}" | grep -q "^[^.]*\.\(0[[:digit:]]\{2\}\)\{2\}"
  then
    dep="$(
      echo "${dep}" | \
        sed "s@^\([^.]*\....\)0\+@\1.@; s@^\([^.]*\.\)0\+@\1@"
    )"
  fi
  erg="${erg}${dep}"
}

versionsUniq() {
  tr ' ' '\n' | \
  sed 's|^perl$|perl>=0|' | \
  sort -rV | \
  sed 's@^\([^<=>]*\)\(\(>=\|=\|<\)[0-9.]*\)$@\1\2 \1@' | \
  sed 's|^\(\S*\)$|\1 \1|' | \
  uniq -f1 "$@" | \
  awk '{print $1}' | \
  sed 's|^perl>=0$|perl|' | \
  sort | \
  grep -v '^\s*$'
}

ladePkgbuild() {
  paket="$1"

  if [[ "${paket}" != "perl-"* ]]; then
    return 1
  fi

  cd "$(dirname "${me}")"
  cd "${paket}"

  makepkg -f --verifysource

  . <(
    sed '
      /^\s*_pinned_dependencies\S*=(.*)/ d
      /^\s*_pinned_dependencies\S*=(/,/)/ d
    ' PKGBUILD
  )
  if grep -qF _pinned_dependencies PKGBUILD; then
    depends+=('"${_pinned_dependencies[@]}"')
  fi
}

versteheMetaYml() {
  archiv="${_distdir}.tar.gz"
  [ -r "${archiv}" ] || archiv="${_distdir}.tgz"

  if [ ! -r "${archiv}" ]; then
    >&2 echo "Kann Quelldatei nicht finden!"
    return 2
  fi

  if ! tar -tzf "${archiv}" "${_distdir}/META.yml"; then

    unset meta

  else

    echo "META.yml lesen ..."

    meta="$(
      tar -Oxzf "${archiv}" "${_distdir}/META.yml" | \
        tr '\r' ' ' | \
        grep -v "^\s*file:" | \
        grep -v "^version:" | \
        sed '
          :begin;
            $!N;
            s@^\(\S.*\)\n\s\+\(\S.*\)$@\1 \2@;
          tbegin;
          P;
          D
        ' | \
        sed "/^provides: /s@\(\s\S\+\):\s\+version:\s\+'\?v\?\([0-9.]\+\)'\?@\L\1=\2@g" | \
        sed "/^provides: /s@\s@  @g" | \
        sed "/^provides: /s@\(\s[^= ]\+\):\+\(\s\|\$\)@\L\1=${pkgver}\2@g" | \
        sed "s@\(\sperl:\s\+\)'\?\([[:digit:]]\+\)\.\([[:digit:]]\{3\}\)'\?\(\s\|\$\)@\1\2.\3.0\4@" | \
        sed "s@\(\sperl:\s\+\)'\?\([[:digit:]]\+\)\.\([[:digit:]]\{3\}\)\([[:digit:]]\+\)'\?\(\s\|\$\)@\1\2.\3.\4\5@" | \
        sed "s@\(\sperl:\s\+\)'\?\([[:digit:]]\+\)[._]0*\([1-9][[:digit:]]*\)[._]0*\([1-9][[:digit:]]*\)'\?\(\s\|\$\)@\1\2.\3.\4\5@" | \
        sed "s@\(\sperl:\s\+\)'\?\([[:digit:]]\+\)[._]0*\([1-9][[:digit:]]*\)[._]0\+'\?\(\s\|\$\)@\1\2.\3.0\4@"
      ! grep -qwF _pinned_dependencies PKGBUILD \
      || printf 'depends:"${_pinned_dependencies[@]}"\n'
    )"

    echo -n "... fertig, "

  fi

  echo "verarbeiten ..."

  set +e

  for sucheWonach in "${!metaRegexe[@]}"; do
    metaInfos["${sucheWonach}"]=""
    for was in $(
      echo "${meta}" | \
        grep "^${metaRegexe["${sucheWonach}"]}:" | \
        sed "s@^${metaRegexe["${sucheWonach}"]}:\s*@@" | \
        sed "s@\(\S\+\):\s\+'\?v\?\([0-9.]*\)'\?\(\s\|\$\)@\L\1>=\L\2\n@g" | \
        sed "s@\(\S\+\):\s\+'\(<=\?\)\s*v\?\([0-9.]\+\)'\(\s\|\$\)@\L\1\2\L\3\n@g" | \
        sed "s@::@-@g" | \
        sed "s|>=0\$||" | \
        grep -v "^\({}\)\?$"
    ); do
      if ${metaSubst["${sucheWonach}"]}; then
        substituiere "${was}"
      else
        erg="perl-${was}"
        if [[ "${erg}" == "${pkgname}="* ]]; then
          erg="perl-%skip"
        fi
      fi
      if echo "${erg}" \
      | grep -q '^perl\([<>=].*\)\?$'; then
        erg='perl-%skip'
      fi
      if [[ "${erg}" != "perl-%skip"* ]]; then
        metaInfos["${sucheWonach}"]="${metaInfos["${sucheWonach}"]} ${erg}"
      fi
    done
    metaInfos["${sucheWonach}"]="$(
      echo "${metaInfos["${sucheWonach}"]}" | \
        versionsUniq | \
        tr ' ' '\n' | \
        mangle_versions | \
        tr '\n' ' '
    )"
  done

  err=false

  for wasAusgeben in "${!metaRegexe[@]}"; do
    eval 'tmp=("${'${wasAusgeben}'[@]}")'
    pkgBuild["${wasAusgeben}"]=$(
      echo "${tmp[@]}" | \
        tr " '" '\n\n' | \
        grep -v '^$' | \
        sort -u
    )
    if [ -z "${pkgBuild["${wasAusgeben}"]}" ] && \
      [ "${wasAusgeben}" == "depends" ]; then
      pkgBuild["${wasAusgeben}"]="perl"
    fi

    metaYml["${wasAusgeben}"]=$(
      {
        echo "${metaInfos["${wasAusgeben}"]}" | \
          grep -v '^$' | \
          grep '^\s*perl'
        echo "${pkgBuild["${wasAusgeben}"]}" | \
          grep -v '^\s*perl'
      } | \
        versionsUniq
    )
    if [ "${wasAusgeben}" == "depends" ]; then
      metaYml["${wasAusgeben}"]=$(
        {
          printf '%s\n' "${metaYml["${wasAusgeben}"]}"
          printf 'perl>=%s\n' "${perlver}"
          printf 'perl<%s.%s\n' "${perlver%%.*}" "$((${perlver#*.}+1))"
        } \
        | sort -u
      )
    fi
    if [ "${wasAusgeben}" == "makedepends" ]; then
      metaYml["${wasAusgeben}"]=$(
        {
          {
            {
              echo "${metaYml["${wasAusgeben}"]}"
              echo "${metaYml["depends"]}"
            } | \
              versionsUniq
            echo "${metaYml["depends"]}"
          } | \
            sort | \
            uniq -d | \
            sed 'p'
          echo "${metaYml["${wasAusgeben}"]}"
        } | \
          versionsUniq -u
      )
    fi
    if ${metaStripVersion["${wasAusgeben}"]}; then
      metaYml["${wasAusgeben}"]=$(
        printf '%s\n' "${metaYml["${wasAusgeben}"]}" | \
          sed '
            s/[<>=]\S\+\( \|$\)/\1/g
          '
      )
    fi
  done
  echo "... fertig"
}

mangle_versions() {
  local pre
  local post
  if [ $# -eq 1 ]; then
    pre="s|^|$1=|"
    post='s|^[^=]*=||'
  fi
  sed "${pre}"'
    /^perl-\(extutils-makemaker\|opengl\)[<>=]/{
      s|\.\([0-9][0-9]\)\([0-9]\+\)|.\1.\2|
    }
  '"${post}"
}

declare -A metaInfos
declare -A metaRegexe
declare -A metaSubst
declare -A metaStripVersion
declare -A metaYml
declare -A pkgBuild

perlver=$(
  perl --version \
  | sed '
    s@^This is perl \([0-9]\+\), version \([0-9]\+\), subversion .*$@\1.\2@
    t
    d
  '
)

metaRegexe["depends"]="requires"
metaSubst["depends"]=true
metaStripVersion["depends"]=false
metaRegexe["makedepends"]="\(build\|configure\)_requires"
metaSubst["makedepends"]=true
metaStripVersion["makedepends"]=false
metaRegexe["optdepends"]="recommends"
metaSubst["optdepends"]=true
metaStripVersion["optdepends"]=true
metaRegexe["conflicts"]="conflicts"
metaSubst["conflicts"]=true
metaStripVersion["conflicts"]=false
metaRegexe["provides"]="provides"
metaSubst["provides"]=false
metaStripVersion["provides"]=false