#!/bin/bash

if [ "x$1" = 'x-n' ]; then
  update=false
  shift
else
  update=true
fi

if [ $# -ne 1 ]
then
  >&2 echo "Verwendung: neuesPerlPaket [-n] cpan-Name"
  exit 1
fi

cpanName="$(echo "$1" | sed 's|::|-|g')"
#url="https://metacpan.org/pod/$1"
url="https://metacpan.org/release/${cpanName}"
pkgname="perl-${cpanName,,}"

me="$(readlink -f "$0")"
cd "$(dirname "${me}")"

if [[ "$1" == "perl-"* ]]
then
  >&2 echo "${1} beginnt mit 'perl-', sollte es aber nicht"
  exit 1
fi

if [ -e "${pkgname}" ]
then
  >&2 echo "${cpanName} gibt es von ewe schon (${pkgname})"
  exit 1
fi

if ls /var/lib/pacman/sync/*.db | \
  grep -v "/\(archlinuxewe\|quarry\)\.db\$" | \
  xargs -rn1 tar -Oxz --wildcards "*/desc" -f | \
  sed '
    :begin;
      $!N;
      s@^\(%[^%]*%.*\)\n\(.\+\)$@\1 \2@;
    tbegin;
    P;
    D
  ' | \
  grep -q "^%\(NAME% ${pkgname}\|PROVIDES%.* ${pkgname}\([= ].*\)\?\)\$"
then
  >&2 echo "${cpanName} gibt es schon offiziell"
  exit 1
fi

. perlFunktionen

seitenInhalt="$(curl -Ss "${url}")"

pkgver="$(
  echo "${seitenInhalt}" | \
    grep "<title>${cpanName}-" | \
    sed "s|^.*<title>${cpanName}-v\?\([0-9.-]\+\)\s.*|\1|"
)"

pkgdesc="$(
  echo "${seitenInhalt}" | \
    grep "<title>${cpanName}-" | \
    sed "s|^.*<title>${cpanName}-v\?[0-9.-]\+\s\+-\s\+\(\S.*\S\)\s\+-\s\+metacpan\.org</title>.*|\1|" | \
    sed "s|'|'\"'\"'|g"
)"

dlUrl="$(
  echo "${seitenInhalt}" | \
    grep "href=\"https://cpan.metacpan.org/authors/id/[^/]/[^/]\{2\}/[^/]\+\(/modules\)\?/${cpanName}-v\?[0-9.]\+\.tar\.gz\">" | \
    sed "s|^.*href=\"\(https://cpan.metacpan.org/authors/id/[^/]/[^/]\{2\}/[^/]\+\(/modules\)\?/${cpanName}-v\?[0-9.]\+\.tar\.gz\)\">.*\$|\1|" | \
    tail -n1
)"

dlUrlForPKGBUILD="$(
  echo "${dlUrl}" | \
    sed "s|/${cpanName}-v\?[0-9.]\+\.tar\.gz|/\${_distdir}.tar.gz|"
)"

mkdir "${pkgname}"
cd "${pkgname}"

wget -nd "${dlUrl}"

if echo "${dlUrl}" | \
  grep -q "/${cpanName}-v[0-9.]\+\.tar\.gz\$"; then
  _distdir="${cpanName}-v${pkgver}"
else
  _distdir="${cpanName}-${pkgver}"
fi

sha512sum="$(
  sha512sum "${_distdir}.tar.gz" | \
    cut -d " " -f 1
)"

echo "META.yml lesen ..."

versteheMetaYml

(
  echo '# Maintainer: Erich Eckner <arch at eckner dot net>'
  echo '# Generator : neuesPerlPaket ('"$(sha512sum "${me}" | cut -d " " -f 1)"')'
  echo ''
  echo "pkgname='${pkgname}'"
  echo "pkgver='${pkgver}'"
  echo "pkgrel='1'"
  echo "pkgdesc='${pkgdesc}'"
  echo "arch=('x86_64' 'i686')"
  echo "license=('PerlArtistic' 'GPL')"
  echo "options=('!emptydirs')"
  for wasAusgeben in "${!metaRegexe[@]}"
  do
    if [ -n "${metaInfos["${wasAusgeben}"]}" ]
    then
      echo "${wasAusgeben}=("
      printf "  '%s'\n" ${metaInfos["${wasAusgeben}"]}
      echo ')'
    fi
  done
  echo "url='${url}'"
  if echo "${dlUrl}" | \
    grep -q "/${cpanName}-v[0-9.]\+\.tar\.gz\$"; then
    echo "_distdir=\"${cpanName}-v\${pkgver}\""
  else
    echo "_distdir=\"${cpanName}-\${pkgver}\""
  fi
  echo "source=(\"${dlUrlForPKGBUILD}\")"
  echo "sha512sums=('${sha512sum}')"
  echo ''
  echo 'build() {'
  echo '  cd "${srcdir}/${_distdir}"'
  echo ''
  echo "  # Setting these env variables overwrites any command-line-options we don't want..."
  echo '  export PERL_MM_USE_DEFAULT=1 PERL_AUTOINSTALL=--skipdeps \'
  echo "    PERL_MM_OPT=\"INSTALLDIRS=vendor DESTDIR='\${pkgdir}'\" \\"
  echo "    PERL_MB_OPT=\"--installdirs vendor --destdir '\${pkgdir}'\" \\"
  echo '    MODULEBUILDRC=/dev/null'
  echo ''
  echo '  # If using Makefile.PL'
  echo '  if [ -r Makefile.PL ]; then'
  echo '    perl Makefile.PL'
  echo '    make'
  echo '  # If using Build.PL'
  echo '  elif [ -r Build.PL ]; then'
  echo '    perl Build.PL'
  echo '    perl Build'
  echo '  fi'
  echo '}'
  echo ''
  echo 'check() {'
  echo '  cd "${srcdir}/${_distdir}"'
  echo ''
  echo '  # If using Makefile.PL'
  echo '  if [ -r Makefile.PL ]; then'
  echo '    make test'
  echo '  # If using Build.PL'
  echo '  elif [ -r Build.PL ]; then'
  echo '    perl Build test'
  echo '  fi'
  echo '}'
  echo ''
  echo 'package() {'
  echo '  cd "${srcdir}/${_distdir}"'
  echo ''
  echo '  # If using Makefile.PL'
  echo '  if [ -r Makefile.PL ]; then'
  echo '    make install'
  echo '  # If using Build.PL'
  echo '  elif [ -r Build.PL ]; then'
  echo '    perl Build install'
  echo '  fi'
  echo ''
  echo '  # remove perllocal.pod and .packlist'
  echo '  find "${pkgdir}" -name .packlist -o -name perllocal.pod -delete'
  echo '}'
) > PKGBUILD

needs_build=true

while ${needs_build}; do

  while ${needs_build}; do
    makepkg -fcrs --noconfirm --asdeps || break
    needs_build=false
    namcap ${pkgname}-*.pkg.tar.xz | \
      tee namcap.log
    if grep -q ' W: No ELF files and not an "any" package$' namcap.log; then
      rm ${pkgname}-*.pkg.tar.xz
      needs_build=true
      sed -i "s/^arch=.*\$/arch=('any')/" PKGBUILD
    fi
 done

  echo ''
  if ${needs_build}; then
    echo 'irgendwas lief schief - kriegst du das wieder hin?'
  else
    echo 'sieht soweit erst mal gut aus, oder?'
  fi
  echo '"": weiter'
  echo 'e: nano PKGBUILD'
  echo 'n *: neuesPerlPaket $@'
  echo 'q: beenden'
  read antwort

  case "${antwort}" in
    '')
    ;;
    'e')
      nano PKGBUILD
      needs_build=true
    ;;
    'n '*)
      for aw in ${antwort#* }; do
        "${me}" -n "${aw}"
      done
      if [ "$(git -C "$(dirname "${me}")" symbolic-ref HEAD 2> /dev/null)" = 'refs/heads/master' ]; then
        "$(dirname "${me}")/archPackagesUpdate" $(printf ' --only %s' ${antwort#* })
        sudo pacman -Sy
      fi
      needs_build=true
    ;;
    *)
      echo 'ok, dann nicht ...'
      exit 1
    ;;
  esac

done

pacman -Qlp ${pkgname}-*.pkg.tar.xz

echo ''
echo 'auch hier alles in Ordnung, oder?'
read antwort

if [ -n "${antwort}" ]
then
  echo 'ok, dann nicht ...'
  exit 1
fi

git add PKGBUILD
git commit -m "${pkgname} neu"

if ${update} && [ "$(git -C "$(dirname "${me}")" symbolic-ref HEAD 2> /dev/null)" = 'refs/heads/master' ]; then
  "$(dirname "${me}")/archPackagesUpdate" --only "${pkgname}"
  sudo pacman -Sy
fi