#!/usr/bin/env bash

#    Copyright 2021 Couchbase, Inc.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

PROJECT_ROOT="$( cd "$(dirname "$0")/../.." >/dev/null 2>&1 ; pwd -P )"

echo "HOSTNAME=${HOSTNAME}"
echo "NODE_NAME=${NODE_NAME}"
echo "CONTAINER_TAG=${CONTAINER_TAG}"
echo "JENKINS_SLAVE_LABELS=${JENKINS_SLAVE_LABELS}"
echo "NODE_LABELS=${NODE_LABELS}"

set -ex

# | CODENAME | RELNAME    |
# +----------+------------+
# | focal    | ubuntu2004 |
# | bionic   | ubuntu1804 |
# | xenial   | ubuntu1604 |
# | buster   | debian10   |
# | stretch  | debian9    |
CODENAME=${CODENAME:-focal}
case "${CODENAME}" in
  focal)
    RELNAME=ubuntu2004
    ;;
  bionic)
    RELNAME=ubuntu1804
    ;;
  xenial)
    RELNAME=ubuntu1604
    ;;
  buster)
    RELNAME=debian10
    ;;
  stretch)
    RELNAME=debian9
    ;;
esac


COW_BASE="/var/cache/pbuilder/${CODENAME}-amd64.cow"
PKGBUILD_ROOT="${PROJECT_ROOT}/pkgbuild"
SOURCES_DIR="${PKGBUILD_ROOT}/sources"
RESULTS_DIR="${PKGBUILD_ROOT}/results"

echo "Building packages in ${COW_BASE}"
echo "Sources: ${SOURCES_DIR}"
echo "Results: ${RESULTS_DIR}"

set -x
set -e


mkdir -p "${SOURCES_DIR}" "${RESULTS_DIR}"

# tarball absolute path written by build-tarball script
TARBALL_NAME=$(cat "${SOURCES_DIR}/tarball-name.txt")
TARBALL_DIR=$(basename "${TARBALL_NAME}" .tar.gz)
# inject build number into release, and copy spec file to build area
BUILD_NUMBER=${BUILD_NUMBER:-1}
VERSION="1.0.0"
DEB_VERSION="${VERSION}~r${BUILD_NUMBER}"
TARBALL_NAME_ORIG=${TARBALL_NAME//-${VERSION}.tar.gz/_${DEB_VERSION}.orig.tar.gz}

cd "${SOURCES_DIR}"
cp "${TARBALL_NAME}" "${TARBALL_NAME_ORIG}"
tar xvf "${TARBALL_NAME}"
cp -a "${PROJECT_ROOT}/scripts/jenkins/pkg/deb/" "${SOURCES_DIR}/${TARBALL_DIR}/debian/"
cd "${SOURCES_DIR}/${TARBALL_DIR}"
dch --no-auto-nmu \
  --package couchbase-transactions \
  --newversion="${DEB_VERSION}-1" \
  --create "Package couchbase-transactions ${DEB_VERSION}-1"
dpkg-buildpackage -rfakeroot -d -S -sa

DSC_NAME=${TARBALL_NAME//-${VERSION}.tar.gz/_${DEB_VERSION}-1.dsc}

cd "${SOURCES_DIR}"
sudo cowbuilder --build \
  --basepath "${COW_BASE}" \
  --buildresult "${RESULTS_DIR}" \
  --debbuildopts -j8 \
  --debbuildopts "-us -uc" \
  "${DSC_NAME}"

cd "${RESULTS_DIR}"
PKG_NAME="couchbase-transactions-${DEB_VERSION}-${RELNAME}-${CODENAME}"
tar cvf "${PKG_NAME}.tar" *.deb
