#!/bin/sh
set -x #trace on
set -e #break on error

APPUSER=${1:-appuser}

# Update APT packages, upgrade existing then delete cache
apt update
apt upgrade -y
rm -rf /var/cache/apt/*

# Add user to run container: appuser
mkdir /home/${APPUSER}
# groupadd airflow
# useradd -r -g airflow airflow
useradd -d /home/${APPUSER} -s /bin/bash -u 1000 -U ${APPUSER}
sed -i -r "s/^${APPUSER}:!:/${APPUSER}:x:/" /etc/shadow
chown ${APPUSER}:${APPUSER} /home/${APPUSER}
echo "${APPUSER} ALL=(ALL) NOPASSWD: ALL" > "/etc/sudoers.d/${APPUSER}"
chmod 0440 /etc/sudoers.d/${APPUSER}

# Remove unnecessary user accounts.
sed -i -r "/^(${APPUSER}|root|sasl)/!d" /etc/group
sed -i -r "/^(${APPUSER}|root|sasl)/!d" /etc/passwd
sed -i -r "/^(${APPUSER}|root|sasl)/!d" /etc/shadow

# Remove interactive login shell for everybody but appuser.
sed -i -r "/^${APPUSER}:/! s#^(.*):[^:]*\$#\1:/sbin/nologin#" /etc/passwd

# Removing files generated by sed commands above (group-, passwd- and shadow-)
# find $sysdirs -xdev -type f -regex '.*-$' -exec rm -f {} +

sysdirs="
  /bin
  /etc
  /lib
  /sbin
  /usr
"

# Ensure system dirs are owned by root and not writable by anybody else.
find $sysdirs -xdev -type d \
  -exec chown root:root {} \; \
  -exec chmod 0755 {} \;

# Remove existing crontabs, if any.
rm -fr /var/spool/cron
rm -fr /etc/crontabs
rm -fr /etc/periodic
  
# Remove init scripts since we do not use them.
rm -fr /etc/init.d
rm -fr /lib/rc
rm -fr /etc/conf.d
rm -fr /etc/inittab
rm -fr /etc/runlevels
rm -fr /etc/rc.conf

# Remove kernel tunables since we do not need them.
rm -fr /etc/sysctl*
rm -fr /etc/modprobe.d
rm -fr /etc/modules

# Remove fstab since we do not need them.
rm -f /etc/fstab

# Remove all but a handful of admin commands.
#find /sbin /usr/sbin ! -type d \
#  -a ! -name nologin \
#  -a ! -name dotnet \
#  -delete

# Remove all but a handful of executable commands.
#find /bin /usr/bin ! -type d \
#  -a ! -name cd \
#  -a ! -name ls \
#  -a ! -name sh \
#  -a ! -name env \
#  -a ! -name bash \
#  -a ! -name dir \
#  -a ! -name rm \
#  -a ! -name dotnet \
#  -a ! -name find \
#  -a ! -name test \
#  -delete

# Remove broken symlinks (because we removed the targets above).
find $sysdirs -xdev -type l -exec test ! -e {} \; -delete
