#!/bin/bash
###============================================================
##      Ubuntu 18.04 Brotli updater
###============================================================
# Make sure to install all Dependencies
#
##=============================================================

#Setting versions variabless
newver=$(apt-show-versions -a nginx:amd64 | grep -o -P '(?<=amd64 ).*(?=~bionic bionic nginx.org)')
curver=$(cat /var/log/nginxVersion.txt)
echo curent=$curver

if [ $newver \> $curver ]; then
  #updating stored versions number
  echo $newver > /var/log/nginxVersion.txt
  # building nginx module
    #source Nginx
    cd /usr/local/src
    git clone --recursive https://github.com/google/ngx_brotli.git
    apt source nginx
    apt build-dep nginx -y

    # building nginx
    cd /usr/local/src/nginx-*/
    sed -i -e 's/ssl_preread_module --with-c/ssl_preread_module --add-module=\/usr\/local\/src\/ngx_brotli --with-c/g' debian/rules
    sudo dpkg-buildpackage -b -uc -us
    
    # moving files, cleaning up and symlinc 
    mv /usr/local/src/*.deb /var/www/brotli-builds
    rm -rf /usr/local/src/*
    ln -f -s /var/www/brotli-builds/nginx-dbg$newver~bionic_amd64.deb /var/www/brotli-builds/nginx-dbg_latest~bionic_amd64.deb
    ln -f -s /var/www/brotli-builds/nginx_$newver~bionic_amd64.deb /var/www/brotli-builds/nginx_latest~bionic_amd64.deb
fi
