#!/bin/bash

set -ex

osc checkout "$OBS_PROJECT" "$OBS_PACKAGE"
cd "$OBS_PROJECT/$OBS_PACKAGE"

rm *.obscpio
osc service disabledrun

# ensure _servicedata ends with a newline
tail -n1 _servicedata | read -r _ || echo >> _servicedata

osc addremove

# Always produced modified files, but only want to bother if new source.
if osc status | grep _servicedata ; then
  echo "new revision found, committing..."
  osc commit -m "$(grep -oP 'version: \K.*' *.obsinfo)"
else
  echo "new revision not found, reverting local changes..."
  osc revert .
fi

if test -z "$OBS_TARGET_PROJECT"; then
  OBS_TARGET_PROJECT="$(osc info | grep -oP "Link info:.*?project \K[^\s,]+")"
fi
if test -z "$OBS_TARGET_PACKAGE"; then
  OBS_TARGET_PACKAGE="$(osc info | grep -oP "Link info:.*?, package \K[^\s,]+")"
  if test -z "$OBS_TARGET_PACKAGE"; then
    OBS_TARGET_PACKAGE=$OBS_PACKAGE
  fi
fi

# Create submit request if none currently exists.
echo "checking for existing requests to $OBS_TARGET_PROJECT/$OBS_TARGET_PACKAGE..."
# `osc request list` is wholly inadequate for the task. :(
if osc api "/search/request?match=(state/@name='declined'+or+state/@name='new'+or+state/@name='review')+and+action/target/@project='$OBS_TARGET_PROJECT'+and+action/target/@package='$OBS_TARGET_PACKAGE'" |
    grep '<collection matches="0">' ; then
  osc service wait
  # Only bother making a request if there is a diff (always 6 lines since
  # binary source tarball dates changed after local run).
  if [ "$(osc sr --diff $OBS_TARGET_PROJECT $OBS_TARGET_PACKAGE | tee temp.diff | wc -l)" -gt 6 ] ; then
    echo "-> creating request"
    cat temp.diff
    rm temp.diff
    osc sr --yes -m "automatic update" $OBS_TARGET_PROJECT $OBS_TARGET_PACKAGE
  else
    echo "-> no difference (likely cron job)"
  fi
else
  echo "-> existing request"
fi
