#! /bin/bash
#
# (C) 2015 jw@owncloud.com
#
# Distribute under GPLv2 or ask.
# 
# service increment_buildrelease
# adds automatic increment of build release numbers to debian and arch linux builds.
# obs only supports this for rpm builds.
#
# modelled after https://github.com/openSUSE/obs-service-format_spec_file/blob/master/format_spec_file

_version=0.3

while test $# -gt 0; do
  case $1 in
    *-outdir)
    OUTDIR="$2"
    shift
  ;;
  *)
    echo Unknown parameter $1.
    echo 'Usage: this service is not accepting parameters'
    exit 1
  ;;
  esac
  shift
done

DSCFILE=$(echo *.dsc)
DEBCHANGE=$(echo *.changelog)
PKGBUILD=$(echo *PKGBUILD)

RETURN=0
# $OUTDIR be identical to . Beware.

if [ "$DSCFILE" != "*.dsc" ]; then
  for f in $DSCFILE; do
    debversionchange=$(osc diff $f | grep '^+Version')
    if [ -z "$debversionchange" ]; then
      echo -n "$f: "
      grep '^Version' $f
      echo "ERROR: version is unchanged. Please increment at least the build release number."
      echo ""
      RETURN=1
    fi
  done
fi

if [ "$DEBCHANGE" != "*.changelog" ]; then
  for f in $DEBCHANGE; do
    deblog_change=$(osc diff $f | grep '^@@ -1,')
    if [ -z "$deblog_change" ]; then
      echo -n "$f: "
      head -n1 $f
      echo "ERROR: version is unchanged. Please increment at least the build release number."
      echo ""
      RETURN=1
    fi
  done
fi

if [ "$PKGBUILD" != "*PKGBUILD" ]; then
  for f in $PKGBUILD; do
    pkgver_change=$(osc diff $f | grep '^+pkgver=')
    pkgrel_change=$(osc diff $f | grep '^+pkgrel=')
    if [ -z "$pkgrel_change$pkgver_change" ]; then
      echo -n "$f: "
      grep '^pkgver=' $f
      echo -n "$f: "
      grep '^pkgrel=' $f
      echo "ERROR: version is unchanged. Please increment at least the build release number."
      echo ""
      RETURN=1
    fi
  done
fi


# echo RETURN $RETURN
# echo PWD $(pwd)
# echo OUTDIR $OUTDIR

if [ $RETURN -ne 0 ]; then
  echo ""
  echo "If you cannot fix the reported errors, you can try to run with --skip-local-service-run"
fi
exit $RETURN

