#!/bin/bash

set -e

if [ $# -eq 0 ]
then
  (
    for s in "$(dirname "$0")"/*
    do
      [ -d "${s}" ] && basename "${s}"
    done
    echo '#kernel'
  ) | parallel -j0 -n1 "$0"
  exit 0
fi

if [ $# -gt 1 ]
then
  for s in "$@"
  do
    echo "${s}"
  done | parallel -j0 -n1 "$0"
  exit 0
fi

if [ "$1" == "#kernel" ]
then
  latestKernelVersion=$(makekernel -s)
  currentKernelVersion=$(
    ls /boot \
    | sed '
      s@^vmlinuz-\([0-9.]\+\)$@\1@
      t
      d
    ' \
    | sort -V \
    | tail -n1
  )

  [ "${currentKernelVersion}" == "${latestKernelVersion}" ] || \
    [ "${currentKernelVersion}" == "${latestKernelVersion}.0" ] || \
    echo "Kernel: ${latestKernelVersion} (installiert: ${currentKernelVersion})"
  exit 0
fi

base=$(dirname "$0")

if [ -x "${base}/$1/lastVersion.sh" ]
then
  newestVersion=$("${base}/$1/lastVersion.sh")
  if [ -z "${newestVersion}" ]
  then
    echo "${base}/$1/lastVersion.sh"' gibt keine Version zurück!'
  fi
fi
lastVersion=$(
  grep "\(^\|\s\)version=" /usr/{src/ports/manualPorts,ports/*}/$1/Pkgfile \
  | cut -d = -f 2 \
  | grep -vxF svn \
  | sort -V \
  | tail -n1
)
myVersion=$(
  grep "\(^\|\s\)version=" /usr/src/ports/manualPorts/$1/Pkgfile \
  | cut -d = -f 2 \
  | sort -V \
  | tail -n1
)

if [ -n "${newestVersion}" ] && \
  [ ! "${newestVersion}" == "${myVersion}" ]
then
  echo "$1: ${newestVersion} upstream verfügbar, bei mir ${myVersion}"
fi
if [ ! "${lastVersion}" == "${myVersion}" ] \
&& [ ! "${lastVersion}" == 'git' ]
then
  echo "$1 gibt es neuer in den offiziellen Quellen!"
  echo /usr/ports/*/$1 | tr " " "\n" | grep -v "/deepthought/"
fi