#!/bin/bash

# AMOS build script for AppArmor

# Copyright 2018 pyllyukko
# 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)

PRGNAM=apparmor
VERSION=${VERSION:-4.1.8}
BUILD=${BUILD:-1}
PKGTYPE=${PKGTYPE:-txz}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) ARCH=i586 ;;
    arm*) ARCH=arm ;;
       *) ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "$PRGNAM-$VERSION-$ARCH-$BUILD.$PKGTYPE"
  exit 0
fi

TMP=${TMP:-/tmp}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

if [ "$ARCH" = "i586" ]; then
  SLKCFLAGS="-O2 -march=i586 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="-O2 -march=i686 -mtune=i686"
  LIBDIRSUFFIX=""
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="-O2 -fPIC -Wl,-z,relro,-z,now -fstack-protector-all -fstack-clash-protection -fcf-protection=full -D_FORTIFY_SOURCE=3 -D_GLIBCXX_ASSERTIONS"
  LIBDIRSUFFIX="64"
else
  SLKCFLAGS="-O2"
  LIBDIRSUFFIX=""
fi

set -e

rm -rf $PKG
mkdir -p $TMP $PKG $OUTPUT
cd $TMP
rm -rf $PRGNAM-$VERSION
tar xvf $CWD/$PRGNAM-v$VERSION.tar.bz2
cd $PRGNAM-v$VERSION
SRCDIR=$(pwd)
export SRCDIR
chown -R root:root .
find -L . \
 \( -perm 777 -o -perm 775 -o -perm 750 -o -perm 711 -o -perm 555 \
  -o -perm 511 \) -exec chmod 755 {} \; -o \
 \( -perm 666 -o -perm 664 -o -perm 640 -o -perm 600 -o -perm 444 \
  -o -perm 440 -o -perm 400 \) -exec chmod 644 {} \;

export PYTHONPATH=$(realpath libraries/libapparmor/swig/python)
export PYTHON=/usr/bin/python3
export PYTHON_VERSION=3
export PYTHON_VERSIONS=python3

pushd ./libraries/libapparmor
sh ./autogen.sh
CFLAGS="$SLKCFLAGS" \
CXXFLAGS="$SLKCFLAGS" \
./configure \
  --prefix=/usr \
  --libdir=/usr/lib${LIBDIRSUFFIX} \
  --sysconfdir=/etc \
  --localstatedir=/var \
  --mandir=/usr/man \
  --docdir=/usr/doc/$PRGNAM-$VERSION \
  --with-perl \
  --with-python \
  --build=$ARCH-amos-linux

make
make install DESTDIR=$PKG
popd

pushd binutils
make
make check
make install DESTDIR=$PKG MANDIR=/usr/man DISTRO=slackware
popd

export DISTRO=slackware
pushd parser
make
make install DESTDIR=$PKG MANDIR=/usr/man
popd
mv -v ${PKG}/etc/apparmor/parser.conf    ${PKG}/etc/apparmor/parser.conf.new
mv -v ${PKG}/etc/rc.d/rc.apparmor        ${PKG}/etc/rc.d/rc.apparmor.new

pushd utils
make
make install DESTDIR=$PKG MANDIR=/usr/man
popd
mv -v ${PKG}/etc/apparmor/easyprof.conf ${PKG}/etc/apparmor/easyprof.conf.new
mv -v ${PKG}/etc/apparmor/logprof.conf  ${PKG}/etc/apparmor/logprof.conf.new
mv -v ${PKG}/etc/apparmor/notify.conf   ${PKG}/etc/apparmor/notify.conf.new
mv -v ${PKG}/etc/apparmor/severity.db   ${PKG}/etc/apparmor/severity.db.new

# Apache
#pushd changehat/mod_apparmor
#make
#make install DESTDIR=$PKG MANDIR=/usr/man
#popd

pushd profiles
make
make install DESTDIR=$PKG
popd

# Prune the shipped profile set down to what is relevant for AM·OS.
#
# The upstream tarball ships ~120 profiles for desktop apps, container
# runtimes, distro-specific tooling and server daemons (samba, dovecot,
# apache2) that are not installed on AM·OS. Loading them all with
# apparmor_parser -r /etc/apparmor.d/ would create dead policy and audit
# noise.
#
# Keep only: basic ping restriction, PAM helper, syslogd/syslog-ng/klogd,
# nscd, ntpd, traceroute. These are all daemons or binaries that are
# installed on an AM·OS node and could benefit from the upstream profiles.
#
# Deliberately NOT kept: php-fpm. The upstream profile assumes systemd
# (@{run}/systemd/notify, @{run}/php-fpm-legacy) and does not match the
# Slackware layout. AM·OS ships its own php-fpm profile below, which
# supersedes the upstream one.
#
# The abi/, abstractions/, tunables/, disable/, local/ and apache2.d/
# directories are include trees and stay as-is.
#
# Run in a subshell so the parent shell's cwd never leaves $SRCDIR.
(
  cd "$PKG/etc/apparmor.d" || exit 1
  rm -f "$TMP/aa-all.txt" "$TMP/aa-keep.txt"
  LC_ALL=C find . -maxdepth 1 -type f -printf '%f\n' | LC_ALL=C sort > "$TMP/aa-all.txt"
  cat > "$TMP/aa-keep.txt" <<'EOF'
bin.ping
sbin.klogd
sbin.syslog-ng
sbin.syslogd
unix-chkpwd
usr.sbin.nscd
usr.sbin.ntpd
usr.sbin.traceroute
sbin.dhcpcd
usr.bin.passwd
usr.sbin.useradd
usr.sbin.userdel
EOF
  comm -23 "$TMP/aa-all.txt" <(LC_ALL=C sort "$TMP/aa-keep.txt") | xargs -r rm -f
) || exit 1

# Install the AM·OS profiles. These are not part of the upstream tarball;
# they live in $CWD/profiles/ and ship with this package so they land in
# /etc/apparmor.d/ on install.
#
# The profiles load at first boot via rc.apparmor (Slackware's rc.M calls
# it before rc.local). They start in complain mode; validating and
# switching to enforce is an administrative action, not an install-time
# one. See /root/README-HARDENING.txt on the target for the workflow.
#
# Five profiles, one per confined service:
#   annode-java   the JVM running the annode application
#   annode-tor    annode's bundled Tor, exec'd from tor-data/
#   tor           system Tor, started only by netmode open
#   mariadbd      MariaDB server
#   php-fpm       FastCGI pool serving annode's PHP servlets
echo "Installing AM·OS profiles from $CWD/profiles/:"

profiles_dir="$CWD/profiles"
[ -d "$profiles_dir" ] || { echo "ERROR: $profiles_dir missing" >&2; exit 1; }

shopt -s nullglob
profiles=( "$profiles_dir"/* )
shopt -u nullglob
[ ${#profiles[@]} -gt 0 ] || { echo "ERROR: no profiles in $profiles_dir" >&2; exit 1; }

for p in "${profiles[@]}"; do
    if [ ! -f "$p" ]; then
        echo "WARNING: skipping non-regular file $p" >&2
        continue
    fi
    install -m 644 -o 0 -g 0 "$p" "$PKG/etc/apparmor.d/$(basename "$p")"
    echo "  $(basename "$p")"
done

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

find $PKG/usr/man -type f -exec gzip -9 {} \;
for i in $( find $PKG/usr/man -type l ) ; do ln -s $( readlink $i ).gz $i.gz ; rm $i ; done

find $PKG -name perllocal.pod \
  -o -name ".packlist" \
  -o -name "*.bs" \
  | xargs rm -f

# Docs. Use absolute paths only — never rely on cwd.
: "${SRCDIR:?SRCDIR is unset or empty}"
mkdir -p "$PKG/usr/doc/$PRGNAM-$VERSION"
cp -a \
  "$SRCDIR/LICENSE" \
  "$SRCDIR/README.md" \
  "$SRCDIR/documentation/" \
  "$PKG/usr/doc/$PRGNAM-$VERSION/"
cat "$CWD/$PRGNAM.SlackBuild" > "$PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild"

rm -f $PKG/usr/lib*/*.la

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

cd $PKG
/sbin/makepkg -l y -c n $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD.$PKGTYPE
