#!/usr/bin/env bash

# Copyright 2018-2023 Istituto Nazionale di Fisica Nucleare
# SPDX-License-Identifier: EUPL-1.2

downloadNginx() {

  # check if ~/rpmbuild exists and is not empty
  if [ -d ${HOME}/rpmbuild ] && [ "$(ls -A ${HOME}/rpmbuild)" ]; then
    >&2 echo "Error: ${HOME}/rpmbuild already exists and is not empty"
    return 1
  fi

  # set nginx version
  if [ -z ${ngxVersion} ]; then
    ngxVersion=1.26.2-1
  fi
  elVersion=$(rpmbuild --eval %{rhel})
  echo "Downloading nginx version ${ngxVersion} (EL${elVersion})"
  src_package_name="nginx-${ngxVersion}.el${elVersion}.ngx.src.rpm"
  src_package_url="https://nginx.org/packages/centos/${elVersion}/SRPMS/${src_package_name}"

  wget ${src_package_url}
  rpm -i ${src_package_name}

}

buildHttpgNginxRPM() {

  if ! printenv CI_PROJECT_DIR > /dev/null; then
    >&2 echo "CI_PROJECT_DIR is not set in the environment, assuming the current working directory '${PWD}'"
    export CI_PROJECT_DIR="${PWD}"
  fi

  sh ${CI_PROJECT_DIR}/rpm/addPatchToNginxSpec.sh

  # build rpm
  rpmlint ~/rpmbuild/SPECS/nginx.spec
  rpmbuild -ba ~/rpmbuild/SPECS/nginx.spec
}

buildVomsModuleRPM() {

  if [ -z ${CI_PROJECT_DIR} ]; then
    CI_PROJECT_DIR="/workspaces/ngx_http_voms_module"
  fi

  # set voms modules sources
  cd ~/rpmbuild/SOURCES/
  mkdir ngx-http-voms-module
  cp ${CI_PROJECT_DIR}/config ngx-http-voms-module/
  cp ${CI_PROJECT_DIR}/config.make ngx-http-voms-module/
  cp -r ${CI_PROJECT_DIR}/src ngx-http-voms-module/
  cp ${CI_PROJECT_DIR}/rpm/nginx-module-http-voms.spec ~/rpmbuild/SPECS

  # build rpm
  rpmlint ~/rpmbuild/SPECS/nginx-module-http-voms.spec
  rpmbuild -ba ~/rpmbuild/SPECS/nginx-module-http-voms.spec

  cd ${CI_PROJECT_DIR}

}
