#!/bin/bash
#
# Used by convert.sh
# Makes file system image suitable for read-only use, and install LDAP client software
#

cat >/etc/fstab <<EOF
proc            /proc                     proc    defaults            0       0

# Locations that need to be writable
# Any location that ordinary users can write to must be nosuid to prevent pam_group privilege escalation
tmpfs           /dev/shm                  tmpfs   defaults,nosuid,nodev,noexec 0       0
tmpfs           /tmp                      tmpfs   defaults,nosuid,nodev        0       0
tmpfs           /var/tmp                  tmpfs   defaults,nosuid,nodev,noexec 0       0
tmpfs           /var/log                  tmpfs   defaults,mode=755,size=100m  0       0
tmpfs           /var/spool                tmpfs   defaults,mode=755            0       0
tmpfs           /var/lib/sudo             tmpfs   defaults,mode=711            0       0
tmpfs           /var/lib/dhcpcd           tmpfs   defaults,mode=755            0       0
tmpfs           /var/lib/bluetooth        tmpfs   defaults,mode=700            0       0
tmpfs           /var/lib/systemd/rfkill   tmpfs   defaults,mode=755            0       0
tmpfs           /var/lib/systemd/coredump tmpfs   defaults,mode=755            0       0
tmpfs           /var/lib/systemd/timesync tmpfs   defaults,mode=755            0       0
tmpfs           /var/lib/systemd/linger   tmpfs   defaults,mode=755            0       0
tmpfs           /media                    tmpfs   defaults,mode=755            0       0
tmpfs           /home                     tmpfs   defaults,mode=755            0       0
piserver:/var/lib/piserver/os/shared   /mnt/shared      nfs     defaults,nolock,nofail,x-gvfs-show,x-gvfs-name=Shared%20folders    0       0
EOF

mkdir -p /mnt/shared

if [ -d /var/lib/dhcpcd5 ] && ! [ -d /var/lib/dhcpcd ]; then
    sed -i 's#/var/lib/dhcpcd #/var/lib/dhcpcd5#g' /etc/fstab
fi

if [ -d /var/cache ]; then
    echo "tmpfs           /var/cache  tmpfs defaults,mode=755                  0       0" >> /etc/fstab
fi

if [ -d /var/lib/lightdm ]; then
    echo "tmpfs           /var/lib/lightdm  tmpfs defaults,uid=lightdm,gid=lightdm,mode=755,nosuid     0       0" >> /etc/fstab
fi

debconf-set-selections <<EOF
nslcd nslcd/ldap-uris string ldap://piserver
nslcd nslcd/ldap-base string dc=raspberrypi,dc=local
libnss-ldapd libnss-ldapd/nsswitch multiselect group, passwd, shadow
EOF

ln -sf /proc/self/mounts /etc/mtab
install -m 700 -d /var/lib/bluetooth
mkdir -p /var/lib/systemd/rfkill
mkdir -p /var/lib/systemd/coredump
mkdir -p /var/lib/systemd/timesync
mkdir -p /var/lib/systemd/linger
rm -f /etc/init.d/apply_noobs_os_config /etc/rc2.d/S01apply_noobs_os_config /etc/init.d/resize2fs_once /etc/rc3.d/resize2fs_once \
    /etc/systemd/system/multi-user.target.wants/regenerate_ssh_host_keys.service

apt-get update
apt-get install -y -q libnss-ldapd libpam-ldapd sshfs libpam-mount
apt-get clean

# Use server's CUPS instance instead of per-client
if [ -d /etc/cups ]; then
	apt-get remove -y -q cups-daemon cups-browsed system-config-printer system-config-printer-common
	apt-get install -y -q cups-client
	apt-get autoremove -y -q
	echo "ServerName piserver" > /etc/cups/client.conf
fi

cat >/etc/security/pam_mount.conf.xml <<EOF
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE pam_mount SYSTEM "pam_mount.conf.xml.dtd">
<pam_mount>
<debug enable="0" />
<volume user="*" fstype="fuse" path="%(USER)@piserver:" mountpoint="/home/%(USER)"
        options="port=1022,password_stdin,UserKnownHostsFile=/dev/null,StrictHostKeyChecking=no,IdentitiesOnly=yes,IdentityFile=/dev/null,ssh_command=ssh -F /dev/null" />

<mntoptions require="nosuid,nodev" />
<logout wait="0" hup="0" term="0" kill="0" />
<mkmountpoint enable="1" remove="true" />
<fusemount>sshfs %(VOLUME) %(MNTPT) -o %(OPTIONS)</fusemount>
</pam_mount>
EOF

# Fix for forced password changes not working properly
# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=862225
if grep -qv disable_interactive /etc/pam.d/common-password; then
    echo "password  optional  pam_mount.so disable_interactive" >> /etc/pam.d/common-password
fi

# Disable user rename
cancel-rename pi
userdel -r rpi-first-boot-wizard
rm -f /etc/sudoers.d/010_wiz-nopasswd
rm -f /etc/xdg/autostart/deluser.desktop

if [ -f /etc/lightdm/lightdm.conf ]; then
    # Disable GUI auto-login
    sed -i "s/^autologin-user=.*/#autologin-user=/" /etc/lightdm/lightdm.conf
    # Store X authority in tmpfs instead of in home dir
    sed -i "s/#user-authority-in-system-dir=false/user-authority-in-system-dir=true/" /etc/lightdm/lightdm.conf
    # Hide user list
    sed -i "s/greeter-hide-users=false/greeter-hide-users=true/" /etc/lightdm/lightdm.conf
fi

# Disable console auto-login
ln -fs /lib/systemd/system/getty@.service /etc/systemd/system/getty.target.wants/getty@tty1.service
rm -f /etc/systemd/system/getty@tty1.service.d/autologin.conf

# No point in saving random seed on read-only system
rm -f "$DISTROROOT"/lib/systemd/system/sysinit.target.wants/systemd-random-seed.service

# systemd-tmpfiles-setup should not try to change files on read-only file system
rm -f /usr/lib/tmpfiles.d/dbus.conf /usr/lib/tmpfiles.d/debian.conf
if [ -f /usr/lib/tmpfiles.d/legacy.conf ]; then
    sed -i 's@L /var/lock @#L /var/lock @g' /usr/lib/tmpfiles.d/legacy.conf
fi
if [ -d /var/lib/dbus ]; then
    ln -sf /etc/machine-id /var/lib/dbus/machine-id
fi

# Use our server as NTP server, as terminals may or may not be able to reach outside ones
if [ -f /etc/ntp.conf ]; then
    sed -i 's/server /#server /g' /etc/ntp.conf
    echo "# Local network boot server" >> /etc/ntp.conf
    echo "server piserver iburst" >> /etc/ntp.conf
elif [ -f /etc/systemd/timesyncd.conf ]; then
    echo "NTP=piserver" >> /etc/systemd/timesyncd.conf
else
    echo "Warning: unable to find NTP configuration file. Configure it manually to use server 'piserver'"
fi

# dhcpcd: disable link detection as we do not want dhcpcd to tear down interface if cable gets disconnected temporarily
if [ -f /etc/dhcpcd.conf ]; then
    echo "nolink" >> /etc/dhcpcd.conf
    {
        echo "# Piserver: disable wifi by default"
        echo "# If you have a need for wifi, remove both the following line, as well as nolink from /etc/dhcpcd.conf"
        echo "dtoverlay=disable-wifi"
    } >> /boot/config.txt
fi

# do not continously poll for SD card
echo "dtparam=sd_poll_once" >> /boot/config.txt

#
# Remove non-relevant options from cmdline.txt
#
sed -i 's# init=\S\+##g' /boot/cmdline.txt
sed -i 's# fsck.repair=yes##g' /boot/cmdline.txt
sed -i 's# rootfstype=ext4##g' /boot/cmdline.txt

# Remove dphys-swapfile and logrotate
apt-get purge -y -q dphys-swapfile logrotate

# Default to disabling per-user browser disk cache
if [ -e /etc/chromium.d ]; then
     # shellcheck disable=SC2016
    echo 'export CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disk-cache-dir=/dev/null --disk-cache-size=1"' >/etc/chromium.d/99-piserver-disable-cache
fi
if [ -e /etc/chromium-browser/customizations ]; then
    # shellcheck disable=SC2016
    echo 'CHROMIUM_FLAGS="$CHROMIUM_FLAGS --disk-cache-dir=/dev/null --disk-cache-size=1"' >/etc/chromium-browser/customizations/99-piserver-disable-cache
fi

# See if user made any customizations as Pi user and make them global
if [ -e /home/pi/.local/share/applications ]; then
    echo "Making Pi user start menu modifications global"
    cp /home/pi/.local/share/applications/*.desktop /usr/share/applications || true
fi

if [ -e /home/pi/.local/share/desktop-directories ]; then
    echo "Making Pi user start menu folder modifications global"
    cp /home/pi/.local/share/desktop-directories/*.directory /usr/share/desktop-directories || true
fi

if [ -e /home/pi/.config/pcmanfm/LXDE-pi ]; then
    echo "Making Pi user desktop appearance setting changes global"
    cp /home/pi/.config/pcmanfm/LXDE-pi/*.conf /etc/xdg/pcmanfm/LXDE-pi || true
fi

#
# User Pi has no place in multi-user system
#
deluser --remove-home pi
delgroup pi

#
# Make all users part of some extra local groups when logged in through lightdm
#
sed -i '/@include common-auth/a auth       optional   pam_group.so' /etc/pam.d/lightdm
{
    echo
    echo "# Added for Piserver"
    echo "lightdm;*;*;Al0000-2400;dialout, audio, video, spi, i2c, gpio, plugdev, input"
} >> /etc/security/group.conf
#echo "login;tty*;*;Al0000-2400;dialout, spi, i2c, gpio" >> /etc/security/group.conf
