#!/bin/bash

# this 'computes' WAIT4DEB_URL and writes it to the env file specifed as $1 (default: upstream.env)

FIRSTCHANGELOG=$(ls -1d debian-*/changelog |head -1)

if [ -z "${FIRSTCHANGELOG}" ] ; then
  echo "Unable to find a debian-*/changelog"
  exit 1
fi
export DEBVER=$(head -1 ${FIRSTCHANGELOG} |sed -e 's/^.*(//' |sed -e 's/).*$//')

FIRSTCONTROL=$(ls -1d debian-*/control |head -1)

if [ -z "${FIRSTCONTROL}" ] ; then
  echo "Unable to find a debian-*/control"
  exit 2
fi

export UPSTREAMENV="$1"
if [ "${UPSTREAMENV}" = "" ] ; then
  UPSTREAMENV="upstream.env"
fi


export PBAREPO=$(egrep "^XBCS-PBA-Repositories: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1)

export PBADISTRO=$(egrep "^XBCS-PBA-Distributions: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1)
test -z "${PBADISTRO}" && PBADISTRO=$(egrep "^XBCS-PBA-Distribution: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1)
export PBADISTFAMILY="debian"
if [ "${PBADISTRO}" = "any" ] ; then
  PBADISTFAMILY="any"
fi

export PBACAT=$(egrep "^XBCS-PBA-Category: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1)

export PBAGEN=$(egrep "^XBCS-PBA-Generation: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1)
BETAVER=$(echo "${DEBVER}" |grep beta)
test -n "${BETAVER}" && PBAGEN="${PBAGEN}beta"

export PBAARCH=$(egrep "^Architecture: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1 |sed -e 's/any/amd64/g')
export PBAPKG=$(egrep "^Package: " ${FIRSTCONTROL} |cut -f2 -d' ' |head -1)

export PBAPROTOCOL="https"
echo "Testing if repo supports https ..."
wget --spider https://${PBAREPO}/ >/dev/null || PBAPROTOCOL="http"
echo "Testing repo reachbility ..."
wget --spider ${PBAPROTOCOL}://${PBAREPO}/ || exit 21

# https?://deb.foobar.com/any/pool/any-cat-1.x/foobar_1.y_all.deb

export WAIT4DEB_URL="${PBAPROTOCOL}://${PBAREPO}/${PBADISTFAMILY}/pool/${PBADISTRO}-${PBACAT}-${PBAGEN}/${PBAPKG}_${DEBVER}_${PBAARCH}.deb"

echo "Computed WAIT4DEB_URL to '${WAIT4DEB_URL}', appending this to ${UPSTREAMENV}"

echo "WAIT4DEB_URL=${WAIT4DEB_URL}" >>${UPSTREAMENV}
echo "WAIT4DEB_PBAGEN=${PBAGEN}" >>${UPSTREAMENV}
