#!/bin/bash

set -eux

apt-get update -y
apt-get install -y alien wget

# This loop is inspired by upstream:
# https://github.com/perl5-dbi/DBD-Oracle/blob/master/maint/scripts/03_install_oracle_instantclient_rpm.bash
#
for component in "basic" "devel" "sqlplus"; do
  # Avoid downloading and running alien if rpm and deb files already exist
  if [ ! -n "$(ls oracle-instantclient-"$component"_*.deb)" ]; then
    if [ ! -f oracle-instantclient-"$component"-linuxx64.rpm ]; then
      wget --quiet "https://download.oracle.com/otn_software/linux/instantclient/oracle-instantclient-$component-linuxx64.rpm"
    fi
    alien --scripts --keep-version oracle-instantclient-"$component"-linuxx64.rpm
  fi
  dpkg -i oracle-instantclient-"$component"_*.deb
done

DEB_BUILD_ARCH=$(dpkg-architecture -q DEB_BUILD_ARCH)
DEB_BUILD_MULTIARCH=$(dpkg-architecture -q DEB_BUILD_MULTIARCH)
CHANGELOG_VERSION=$(dpkg-parsechangelog -S Version)

apt-get build-dep -y .
# Tweak to avoid bugs.debian.org/1072471
ln -snf libaio.so.1t64 /usr/lib/"$DEB_BUILD_MULTIARCH"/libaio.so.1
dpkg-buildpackage -b
apt-get install -y ../libdbd-oracle-perl_"$CHANGELOG_VERSION"_"$DEB_BUILD_ARCH".deb
prove
