#!/bin/sh -xe

if [[ -z "${GITHUB_REF_NAME}" || -z "${NGINX_VERSION}" || -z "${OSC_REPO}" || -z "${OSC_PKG}"  ]]; then
  exit -1
fi

rm -rf osc_data

echo "OSC BUILD : USING NGINX ${NGINX_VERSION} AND TAG ${GITHUB_REF_NAME}"
NGINX_DOME_VERSION=${GITHUB_REF_NAME}
# PACKAGE SOURCE AND CONFIG FILES FOR OSC BUILD
mkdir NginxDome-${NGINX_DOME_VERSION}
cp $(find . -not -path '*/.*' -type f -maxdepth 1) NginxDome-${NGINX_DOME_VERSION}
tar -czvf NginxDome-${NGINX_DOME_VERSION}-new.tar.gz NginxDome-${NGINX_DOME_VERSION}
rm -rf NginxDome-${NGINX_DOME_VERSION}

# INSTALL AND CONFIG
sudo apt install -y osc
sudo mkdir -p /root/.config/osc
cp .github/scripts/oscrc ~/.config/osc/oscrc
sed -i "s|OSC_PSW|${OPENSUSE_PWD}|g" ~/.config/osc/oscrc

# CHECKOUT PACKAGE
osc checkout -o osc_data ${OSC_REPO} ${OSC_PKG}
pushd osc_data
REVISION=$(osc info | grep Revision | awk '{print $2}')

# DOWNLOAD NGINX SOURCE AND MOVING DATADOME PACKAGE INSIDE osc_data FOLDER
curl http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz > nginx-${NGINX_VERSION}.tar.gz
mv ../NginxDome-${NGINX_DOME_VERSION}-new.tar.gz NginxDome-${NGINX_DOME_VERSION}.tar.gz

# RECREATE PACKAGE WITH NEW CONTENT
rm -rf debian
tar xzf debian.tar.gz
sed -e "s:@@NGINX_VERSION@@:${NGINX_VERSION}:g; s:@@NGINX_DATADOME_VERSION@@:${NGINX_DOME_VERSION}:g" nginx-datadome.spec.in > nginx-datadome.spec
sed -e "s:@@NGINX_VERSION@@:${NGINX_VERSION}:g; s:@@NGINX_DATADOME_VERSION@@:${NGINX_DOME_VERSION}:g; s:@@REVISION@@:${REVISION}:g" debian/changelog.in > debian/changelog
sed -e "s:@@NGINX_VERSION@@:${NGINX_VERSION}:g; s:@@NGINX_DATADOME_VERSION@@:${NGINX_DOME_VERSION}:g; s:@@REVISION@@:${REVISION}:g" nginx.dsc.in > nginx.dsc
rm -rf debian/extra/NginxDome
mkdir -p debian/extra/NginxDome
tar -xvz --strip-components=1 -C debian/extra/NginxDome -f NginxDome-${NGINX_DOME_VERSION}.tar.gz
echo "${NGINX_VERSION}.${NGINX_DOME_VERSION}" > debian/nginx-module-datadome.version
tar -czf nginx-debian.tar.gz debian
osc add nginx-${NGINX_VERSION}.tar.gz || :
osc add NginxDome-${NGINX_DOME_VERSION}.tar.gz || :
osc commit -m "[GHA] Add build for Nginx ${NGINX_VERSION} with DataDome module ${NGINX_DOME_VERSION} revision ${REVISION}"
popd

