#!/bin/bash

# Copyright 2021-2023  Heinz Wiesinger, Amsterdam, The Netherlands
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

cd $(dirname $0) ; CWD=$(pwd)

PKGNAM=nginx
VERSION=${VERSION:-$(echo $PKGNAM-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
GEOIP2_VERSION=${GEOIP2_VERSION:-$(echo ngx_http_geoip2_module-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
FANCYINDEX_VERSION=${FANCYINDEX_VERSION:-$(echo ngx-fancyindex-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
ECHO_VERSION=${ECHO_VERSION:-$(echo echo-nginx-module-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
SASS_VERSION=${SASS_VERSION:-$(echo ngx-sass-module-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
NJS_VERSION=${NJS_VERSION:-$(echo njs-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
BUILD=${BUILD:-1}

# Automatically determine the architecture we're building on:
if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) export ARCH=i586 ;;
    arm*) export ARCH=arm ;;
    # Unless $ARCH is already set, use uname -m for all other archs:
       *) export ARCH=$( uname -m ) ;;
  esac
fi

# If the variable PRINT_PACKAGE_NAME is set, then this script will report what
# the name of the created package would be, and then exit. This information
# could be useful to other scripts.
if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PKGNAM-$VERSION-$ARCH-$BUILD.txz"
  exit 0
fi

TMP=${TMP:-/tmp}
PKG=$TMP/package-${PKGNAM}
rm -rf $PKG
mkdir -p $TMP $PKG

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "s390" ]; then
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

NUMJOBS=${NUMJOBS:-" -j $(expr $(nproc) + 1) "}

cd $TMP
rm -rf ${PKGNAM}-${VERSION}
tar xvf $CWD/${PKGNAM}-$VERSION.tar.?z || exit 1
rm -rf ngx_http_geoip2_module-${GEOIP2_VERSION}
tar xvf $CWD/ngx_http_geoip2_module-${GEOIP2_VERSION}.tar.?z || exit 1
rm -rf ngx-fancyindex-${FANCYINDEX_VERSION}
tar xvf $CWD/ngx-fancyindex-${FANCYINDEX_VERSION}.tar.?z || exit 1
rm -rf echo-nginx-module-${ECHO_VERSION}
tar xvf $CWD/echo-nginx-module-${ECHO_VERSION}.tar.?z || exit 1
rm -rf ngx-sass-module-${SASS_VERSION}
tar xvf $CWD/ngx-sass-module-${SASS_VERSION}.tar.?z || exit 1
rm -rf njs-${NJS_VERSION}
tar xvf $CWD/njs-${NJS_VERSION}.tar.?z || exit 1
cd ${PKGNAM}-$VERSION || exit 1

# Make sure ownerships and permissions are sane:
chown -R root:root .
find . \
  \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
  -exec chmod 755 {} \+ -o \
  \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
  -exec chmod 644 {} \+

./configure \
    --prefix=/etc/nginx \
    --sbin-path=/usr/sbin/nginx \
    --modules-path=/usr/lib$LIBDIRSUFFIX/nginx/modules \
    --conf-path=/etc/nginx/nginx.conf \
    --error-log-path=/var/log/nginx/error.log \
    --http-log-path=/var/log/nginx/access.log \
    --pid-path=/var/run/nginx.pid \
    --lock-path=/var/run/nginx.lock \
    --http-client-body-temp-path=/var/cache/nginx/client_temp \
    --http-proxy-temp-path=/var/cache/nginx/proxy_temp \
    --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp \
    --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp \
    --http-scgi-temp-path=/var/cache/nginx/scgi_temp \
    --user=nginx \
    --group=nginx \
    --with-compat \
    --with-file-aio \
    --with-threads \
    --with-http_addition_module \
    --with-http_auth_request_module \
    --with-http_dav_module \
    --with-http_flv_module \
    --with-http_gunzip_module \
    --with-http_gzip_static_module \
    --with-http_mp4_module \
    --with-http_random_index_module \
    --with-http_realip_module \
    --with-http_secure_link_module \
    --with-http_slice_module \
    --with-http_ssl_module \
    --with-http_stub_status_module \
    --with-http_sub_module \
    --with-http_v2_module \
    --with-mail \
    --with-mail_ssl_module \
    --with-stream \
    --with-stream_realip_module \
    --with-stream_ssl_module \
    --with-stream_ssl_preread_module \
    --with-http_xslt_module=dynamic \
    --with-http_image_filter_module=dynamic \
    --with-http_perl_module=dynamic \
    --add-dynamic-module=$TMP/ngx_http_geoip2_module-$GEOIP2_VERSION \
    --add-dynamic-module=$TMP/ngx-fancyindex-${FANCYINDEX_VERSION} \
    --add-dynamic-module=$TMP/echo-nginx-module-${ECHO_VERSION} \
    --add-dynamic-module=$TMP/ngx-sass-module-${SASS_VERSION} \
    --add-dynamic-module=$TMP/njs-${NJS_VERSION}/nginx \
    --with-cc-opt="$SLKCFLAGS -Wno-dangling-pointer -Wno-maybe-uninitialized"

# Build and install:
make $NUMJOBS INSTALLDIRS=vendor INSTALLVENDORMAN3DIR=/usr/man/man3 || exit 1
make install INSTALLDIRS=vendor INSTALLVENDORMAN3DIR=/usr/man/man3 DESTDIR=$PKG || exit 1

# Install init script
mkdir -p $PKG/etc/rc.d
sed -e 's|%DEFAULTSTART%|2 3 4 5|g' -e 's|%DEFAULTSTOP%|0 1 6|g' \
    -e 's|%PROVIDES%|nginx|g' $CWD/rc.nginx > $PKG/etc/rc.d/rc.nginx.new

# Install logrotate config
mkdir -p $PKG/etc/logrotate.d
install -m 644 $CWD/nginx.logrotate $PKG/etc/logrotate.d/nginx

# Move default html files to /usr/share
mkdir -p $PKG/usr/share/nginx
mv $PKG/etc/nginx/html $PKG/usr/share/nginx/

# Remove default config files
rm -f $PKG/etc/nginx/*.default

# Don't clobber existing config files
cd $PKG/etc/nginx/
  for i in *; do
    mv "$i" "$i.new"
  done
cd -

# Install config for a default vhost
mkdir -p $PKG/etc/nginx/conf.d
install -m 644 $CWD/nginx.vh.default.conf $PKG/etc/nginx/conf.d/default.conf.new

# Replace default nginx.conf to make use of the conf.d directory out-of-the-box
install -m 644 $CWD/nginx.conf $PKG/etc/nginx/nginx.conf.new

# Link dynamic modules directory into /etc so we can use relative paths
ln -s /usr/lib$LIBDIRSUFFIX/nginx/modules $PKG/etc/nginx/

# Set up /var/cache
mkdir -p $PKG/var/cache/nginx
chmod 755 $PKG/var/cache/nginx

# Strip binaries:
find $PKG | xargs file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null

# Compress and link manpages, if any:
if [ -d $PKG/usr/man ]; then
  ( cd $PKG/usr/man
    for manpagedir in $(find . -type d -name "man*") ; do
      ( cd $manpagedir
        for eachpage in $( find . -type l -maxdepth 1) ; do
          ln -s $( readlink $eachpage ).gz $eachpage.gz
          rm $eachpage
        done
        gzip -9 *.*
      )
    done
  )
fi

# Remove perllocal files:
( cd $PKG ; find . -name perllocal.pod -exec rm "{}" \+ )

# This removes our DESTDIR from the packlist filenames, to keep perl's
# internal inventories consistent and correct.
find $PKG -name .packlist | while read plist ; do
  sed -e "s%$PKG%%g" \
      -e "s%/share/man%/man%g" \
      -re "s%\.([1-9]n?|3pm)$%&.gz%g   # extend man filenames for .gz" \
      ${plist} > ${plist}.new
      mv -f ${plist}.new ${plist}
done

mkdir -p $PKG/usr/doc/nginx-$VERSION
cp -a CHANGES LICENSE README $PKG/usr/doc/nginx-$VERSION

mkdir -p $PKG/install
zcat $CWD/doinst.sh.gz > $PKG/install/doinst.sh
cat $CWD/slack-desc > $PKG/install/slack-desc

cd $PKG
/sbin/makepkg -l y -c n $TMP/${PKGNAM}-$VERSION-$ARCH-$BUILD.txz

