#!/bin/bash

# Copyright 2019 Google 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.

# Description:
# Builds the nginx-sxg plugin deb packages. The script must be run at the root
# directory of the nginx-sxg source tree. The deb packages will be copied to
# the current directory.
#
# This script is written mainly for CI.

set -ex

readonly SRCDIR="${PWD}"
readonly DESTDIR="${SRCDIR}/$1"
readonly WORKDIR="$(mktemp -d)"

echo "Working in ${WORKDIR}"
cd "${WORKDIR}"

apt-get source nginx-full
cd nginx-*
sed -i \
  -e "s|^common_configure_flags := |common_configure_flags := --add-dynamic-module=${SRCDIR} |g" \
  -e "s/^DYN_MODS := /DYN_MODS := http-sxg-filter /g" debian/rules
sed -i \
  -e "s/libssl-dev,/libssl-dev, libsxg-dev,/" \
  -e "s/Maintainer: .*$/Maintainer: Hiroki Kumazaki <kumagi@google.com>/" debian/control

# The empty line separates the description from previous one already in
# debian/control.
cat << 'EOF' >> debian/control

Package: libnginx-mod-http-sxg-filter
Architecture: any
Depends: libsxg0 (>= 0.2),
         ${misc:Depends},
         ${shlibs:Depends}
Description: Signed HTTP Exchange filter module for nginx.
 An nginx module that generates SXG response from upstream when clients request
 it.
EOF

cp debian/libnginx-mod.nginx.skeleton debian/libnginx-mod-http-sxg-filter.nginx
echo 'load_module modules/ngx_http_sxg_filter_module.so;' \
  > debian/libnginx-mod.conf/mod-http-sxg-filter.conf

debuild -us -uc

mv ../libnginx-mod-http-sxg-filter_*.deb "${DESTDIR}"
cd ../..
rm -rf "${WORKDIR}"
dpkg -I ${DESTDIR}/libnginx-mod-http-sxg-filter_*.deb

echo "Successfully generated .deb file"
