#!/bin/sh
# Copyright (C) James Budiono 2013, 2014, 2015
# License: GNU GPL Version 3 or later.
#
# Fatdog RootFS final adjustment script
# Run this last - just before makesfs
# . = ROOT

### configuration
SPOT_HOME=./$(awk -F: '$1=="spot" {print $6}' ./etc/passwd)
FTP_HOME=./$(awk -F: '$1=="ftp" {print $6}' ./etc/passwd)
SPOT_DIR_MODE=2750 # spot dirmode, same as in mkuser.sh
ROOT_DIR_MODE=700  # /root dirmode, change to 700 for most restrictive
MERGE_FIREFOX_SEAMONKEY= # 'yes' to do it, or leave blank to disable
MERGE_SEAMONKEY_LIBREOFFICE_DICT=yes # 'yes' to do it, or leave blank to disable
XDG_DEFAULT_LIST=usr/share/applications/defaults.list
BB_DISABLE_USR="s@^usr/@@"    # or blank - for sed
BB_EXCLUDED_LIST="||"         # or blank - for case
SETUID_BINARIES="
bin/busybox-cron
bin/busybox-login
bin/passwd
bin/su
sbin/crond
usr/libexec/ssh-keysign
usr/libexec/dbus-daemon-launch-helper
usr/libexec/Xorg.wrap
usr/bin/gtksu
usr/bin/Xorg
usr/bin/screen-4.6-2
bin/fusermount
bin/fusermount3
usr/bin/fbterm
usr/bin/newuidmap
usr/bin/newgidmap
usr/libexec/lxc/lxc-user-nic
usr/bin/xtrlock.bin
usr/bin/bwrap
"

### helpers ###

# $1-path
create_bbwrapper() {
	local appletname=${1##*/}
	rm $1
	cat > $1 << EOF
#!/bin/ash
exec busybox $appletname "\$@"
EOF
	chmod +x $1
}

# $1-old name $2-new name
rename_binary() {
	if readlink -f $1 | grep -q busybox; then
		create_bbwrapper $1
	fi
	mv $1 $2
}

# re-symlink busybox applet to the non-busybox versions
# $1-full binary (must exist) $1-bb symlink
resymlink_bb_applet() {
	if readlink -f $2 | grep -q busybox; then
		rm -f $2
		ln -s $1 $2
	fi
}

# $1-cmd $2-params etc
create_xdg_startup_wrapper() {
	local target=./etc/xdg/Startup/${1##*/}
	rm -f $target
	cat > $target << EOF
#!/bin/dash
exec $*
EOF
	chmod +x $target
}

### main ###
# 1. remove fossil placeholders
echo cleanup ...
find . -name placeholder_for_fossil -delete

# 2. dirs we can't create earlier: dev proc sys archive tmp
echo dev proc sys tmp archive dir...
mkdir -p dev proc sys archive tmp
chown root:users archive
chmod 1770 archive
chmod 1777 tmp var/tmp

# 3. Create busybox symlinks, if needed
if [ -e bin/busybox-applet-list ]; then
	sed "$BB_DISABLE_USR" < bin/busybox-applet-list |
	while read -r p; do
		case "$BB_EXCLUDED_LIST" in
			*"|${p##*/}|"*) continue ;;
		esac
		if ! [ -e $p ]; then 
			ln -s ../bin/busybox $p # let it fail when something else already exists
		fi
	done
fi

# 4. default shell is bash
echo symlinks...
ln -sf bash bin/sh 

# 5. mtab
ln -sf /proc/mounts etc/mtab

# 6. adjust mount & umount - NO LONGER NEEDED - we use mountmon now
#rename_binary bin/mount bin/mount-FULL
#rename_binary bin/umount bin/umount-FULL
#ln -sf fatdog-mount-wrapper.sh bin/mount
#ln -sf fatdog-mount-wrapper.sh bin/umount

# 7. adjust losetup & udevd - NO LONGER NEEDED - we run with full losetup now
#    All scripts must be able to cope with both FULL and busybox version of losetup
#    If it requires busybox version, then just run "busybox losetup"
#rename_binary sbin/losetup sbin/losetup-FULL
#ln -sf /bin/busybox sbin/losetup
ln -sf losetup sbin/losetup-FULL # compatibility for scripts that expects losetup-FULL
#ln -sf /lib64/udev/udevd sbin/udevd

# 8. xauth & sftp-server for dropbear
mkdir -p usr/bin/X11 usr/libexec
ln -sf /usr/bin/xauth usr/bin/X11/xauth
#ln -sf /usr/lib64/openssh/xauth usr/libexec/sftp-server # already there

# 9. rgb.txt for older programs
mkdir -p usr/lib/X11 usr/lib64/X11
ln -sf /usr/share/X11/rgb.txt usr/lib/X11/rgb.txt
ln -sf /usr/share/X11/rgb.txt usr/lib64/X11/rgb.txt

# 10. override initrd binaries (not needed anymore)
#ln -sf /usr/bin/awk bin/awk
#ln -sf /usr/bin/du bin/du
#ln -sf /usr/bin/echo bin/echo
#ln -sf /usr/bin/true bin/true

# 10a. GTK theme: 
[ -e ./usr/bin/rox ] && echo 'gtk-icon-theme-name="ROX"' > ./root/.gtkrc.mine
[ -e ./root/.gtkrc.mine ] && [ -e ./usr/bin/gtk-theme-switch2 ] && ln -sf .gtkrc.mine ./root/.gtkrc-2.0.mine

# 10b. certain items we want to copy from root to spot
#      so we don't have to maintain multiple copies
cp -a ./root/.icons ./root/.local ./root/.cache ./root/.config \
      ./root/.xinitrc ./root/.xserverrc ./root/Startup         \
      ./root/.gtkrc* ./root/.jwm* ./root/.fatdog ./root/.sven  \
      ./root/.gtk-bookmarks $SPOT_HOME

# 11. permissions
echo setting permissions ...
find . -type f -print0 | xargs -0 chmod -s # turn off all setuid 
chmod $ROOT_DIR_MODE root # restrict access for root
chmod 711 home            # restrict access for home
chown -Rh spot:spot $SPOT_HOME  # make sure spot owns everything in spot
chown -Rh ftp:ftp $FTP_HOME     # make sure ftp owns everything in /home/ftp
chmod $SPOT_DIR_MODE $SPOT_HOME # and set spot's home dir permission
chmod +s $SETUID_BINARIES 2> /dev/null # turn on setuid again for specific binaries
# cups - ensure backend and filters have the right permissions
chown root:root usr/lib64/cups/backend/* usr/lib64/cups/filter/* \
                usr/lib64/cups/backend   usr/lib64/cups/filter
chmod 0755 usr/lib64/cups/backend usr/lib64/cups/filter usr/lib64/cups/filter/*
chmod 0500 usr/lib64/cups/backend/* # otherwise won't run as root
chown -Rh webuser:webgroup var/lib/www # default webroot for mongoose
chmod 0600 etc/shadow etc/gtksudoer # make sure it is not available to anyone
chown root:messagebus usr/libexec/dbus-daemon-launch-helper var/run/dbus
chmod 4750 usr/libexec/dbus-daemon-launch-helper
chmod 0600 etc/wpa_supplicant.conf

# 12. symlink optional, missing, and startup programs 
[ ! -e usr/bin/xterm -a -e usr/bin/urxvt ] && ln -sf urxvt usr/bin/xterm
[ ! -e usr/bin/rxvt  -a -e usr/bin/urxvt ] && ln -sf urxvt usr/bin/rxvt
if [ -e usr/bin/gtkdialog ]; then # gtkdialog is main binary now
	! [ -e usr/bin/gtkdialog3 ] && ln -sf gtkdialog usr/bin/gtkdialog3
	! [ -e usr/bin/gtkdialog4 ] && ln -sf gtkdialog usr/bin/gtkdialog4
fi
[ -e usr/bin/glipper-lite ] && create_xdg_startup_wrapper glipper-lite
[ -e usr/bin/sven ] && create_xdg_startup_wrapper sven
[ -e usr/bin/xscreenshot ] && create_xdg_startup_wrapper xscreenshot -k 'Print'
[ -e usr/bin/retrovol ] && chmod +x etc/xdg/Startup/retrovol
[ -e usr/sbin/wpa_gui ] && chmod +x etc/xdg/Startup/WpaGui
[ -e usr/bin/autochown ] && chmod +x etc/init.d/91-autochownd

# 13. replace the "-" in SendTo items with spaces
find etc/xdg/rox.sourceforge.net/SendTo/ ! -type d | while read -r p; do
	file="${p##*/}" dir="${p%/$file}"
	case "$file" in
		*-*) mv "$p" "$dir/$(echo "$file" | tr '-' ' ')" ;;
	esac
done

# 14. Update important cache files (e.g. mime-database, font.dir/font.scale)
update-mime-database usr/share/mime
for p in usr/share/fonts/X11/*; do # compensate for packages which fail to update fonts.dir
	mkfontscale "$p"
	mkfontdir "$p"
done
rm -f usr/share/info/dir
for p in usr/share/info/*info; do # compensate for packages which fails
	install-info --dir-file=usr/share/info/dir $p
done
chroot . /usr/bin/gtk-query-immodules-2.0 --update-cache
chroot . /usr/bin/gdk-pixbuf-query-loaders --update-cache
glib-compile-schemas ./usr/share/glib-2.0/schemas

# 15. Sync all mime and set default programs
./usr/bin/fatdog-sync-mime.sh .

# 16. Remove bad libraries (e.g. vdpau for nouveau)
rm -f usr/lib64/vdpau/*nouveau*

# 17. make firefox re-use gecko libs from seamonkey
# (both must be installed, and they must use identical gecko version)
if [ "$MERGE_FIREFOX_SEAMONKEY" ] && [ -e usr/lib64/firefox ] && [ -e usr/lib64/seamonkey ]; 
then
	SM=$(readlink usr/lib64/seamonkey) # link to actual seamonkey dir
	rm usr/lib64/firefox/*.so usr/lib64/firefox/*.chk
	for p in $(ls usr/lib64/seamonkey); do
		case $p in
			*.so|*.chk) ln -sf /usr/lib64/$SM/$p usr/lib64/firefox/$p
		esac
	done	
fi

# 18. make Seamonkey use Libreoffice dictionary if both are available
if [ "$MERGE_SEAMONKEY_LIBREOFFICE_DICT" ] &&
   [ -e usr/lib64/seamonkey ] && 
   [ -e usr/lib64/libreoffice/share/extensions/dict-en ]; 
then
	SM=$(readlink usr/lib64/seamonkey) # link to actual seamonkey dir
	rm -rf usr/lib64/$SM/dictionaries
	ln -sf /usr/lib64/libreoffice/share/extensions/dict-en usr/lib64/$SM/dictionaries
fi

# 19. run i18n on desktop files (from L18L)
[ -x usr/sbin/update-desktop-files-i18n.sh ] &&
usr/sbin/update-desktop-files-i18n.sh usr/share/L18L/desktop/my_desktop_infos_*

# 20. Enable CUPS to use PDF workflow by default (drop ghostscript dependency)
# Make pstops have higher cost than pdftopdf, so PDF workflow is enabled
# Ref: https://wiki.linuxfoundation.org/openprinting/pdf_as_standard_print_job_format
sed -i -r -e '/\spstops$/ { s/66/100/ }' usr/share/cups/mime/mime.convs
# if ghostscript is not installed, use pdftoraster instead of gstoraster
# by making the cost of pdftoraster lower than gstoraster.
# Ref: https://lists.linuxfoundation.org/pipermail/printing-architecture/2014/002860.html
! test -e ./usr/bin/gs &&
sed -i -e '\|application/vnd.cups-raster| s/100/98/' ./usr/share/cups/mime/cupsfilters-poppler.convs 

# 21. Replace busybox readlink with the proper one (fixes VirtualBox installation)
resymlink_bb_applet /usr/bin/readlink ./bin/readlink

# 22. Create /etc/defaultprograms.template from /etc/defaultprograms
cat - ./etc/defaultprograms > ./etc/defaultprograms.template << "EOF"
#
# System Template for default programs
# __DO NOT__ edit this file - it gets updated on a new release.
#
EOF

# 23. Run update-desktop-database to make sure that mimeinfo.cache is updated
chroot . /usr/bin/update-desktop-database

# done
#rm $0 # self-destruct
