#!/bin/bash

MYDIR=`pwd`
cd / >/dev/null

ln -sf /proc/mounts etc/mtab

# omit syncing for all log files
# Disable klog
CFG_FILE=etc/rsyslog.conf
if [ -f $CFG_FILE ]; then
    cat $CFG_FILE | sed -e "s,^\$ModLoad imklog,#\$ModLoad imklog,g" \
        -e "s,[[:blank:]]/var/log/, -/var/log/,g" > ${CFG_FILE}.$$
    if [ $? -eq 0 ]; then
        chown --reference=${CFG_FILE} $CFG_FILE.$$ || exit 1 > /dev/null 2>&1
	chmod --reference=${CFG_FILE} $CFG_FILE.$$ || exit 1 > /dev/null 2>&1
	mv -f $CFG_FILE.$$ ${CFG_FILE} > /dev/null 2>&1
    fi
fi

# Enable root login
CFG_FILE=etc/ssh/sshd_config
if [ -f $CFG_FILE ]; then
    cat $CFG_FILE | sed "s,^#PermitRootLogin.*,PermitRootLogin yes,g" > ${CFG_FILE}.$$
    if [ $? -eq 0 ]; then
        chown --reference=${CFG_FILE} $CFG_FILE.$$ || exit 1 > /dev/null 2>&1
	chmod --reference=${CFG_FILE} $CFG_FILE.$$ || exit 1 > /dev/null 2>&1
	mv -f $CFG_FILE.$$ ${CFG_FILE} > /dev/null 2>&1
    fi
fi

# Convert system to shadow password files
usr/sbin/pwconv

# Set default target as multi-user target
rm -f lib/systemd/system/default.target > /dev/null 2>&1
ln -s multi-user.target lib/systemd/system/default.target > /dev/null 2>&1
mkdir -p etc/systemd/system/default.target.wants > /dev/null 2>&1

# turn off and stop some services
for i in named bind9 quotarpc fetchmail ondemand rsync uuidd wide-dhcpv6-client; do
	systemctl stop $i > /dev/null 2>&1
	systemctl disable $i > /dev/null 2>&1
done

# for upstart services comment out the start on in confs
for i in nmbd smbd samba-ad-dc rpcbind; do
	systemctl disable $i > /dev/null 2>&1
done

# PSBM-163931: mask units that always fail inside a container and leave systemd
# in a "degraded" state: root/fs is container-managed (remount-fs tries to
# remount /dev/pts and fails), the template uses ifupdown not networkd
# (networkd-wait-online has nothing to wait for), and ifupdown-pre runs
# "udevadm settle" whenever an interface is configured -- which fails in a
# container ("Failed to wait for daemon to reply") because there is no real
# udevd, turning every networked CT degraded. networking.service only Wants
# (not Requires) ifupdown-pre, so masking it is safe.
for u in systemd-remount-fs.service systemd-networkd-wait-online.service ifupdown-pre.service; do
	ln -sf /dev/null etc/systemd/system/$u
done

for fw in iptables ip6tables arptables ebtables; do
	update-alternatives --set $fw /usr/sbin/$fw-legacy > /dev/null 2>&1
done

# export PATH
CFG_FILE=etc/bash.bashrc
if [ -f $CFG_FILE ] ; then
	echo >> $CFG_FILE
	echo "export PATH" >> $CFG_FILE
	echo >> $CFG_FILE
fi

# apache tuning
for worker in mpm_worker mpm_prefork mpm_event; do
	CFG_FILE=etc/apache2/mods-available/$worker.conf
	if [ -f $CFG_FILE ]; then
	    sed -e "s/^[[:blank:]]*StartServers[[:blank:]]*.*/StartServers       1/" \
		-e "s/^[[:blank:]]*MinSpareServers[[:blank:]]*.*/MinSpareServers    1/" \
		-e "s/^[[:blank:]]*MaxSpareServers[[:blank:]]*.*/MaxSpareServers    5/" \
		-e "s/^[[:blank:]]*MaxClients[[:blank:]]*.*/MaxClients        10/" \
		-e "s/^[[:blank:]]*MinSpareThreads[[:blank:]]*.*/MinSpareThreads    1/" \
		-e "s/^[[:blank:]]*MaxSpareThreads[[:blank:]]*.*/MaxSpareThreads    4/" \
		$CFG_FILE > ${CFG_FILE}.$$
		if [ $? -eq 0 ]; then
		        chown --reference=${CFG_FILE} $CFG_FILE.$$ || exit 1 > /dev/null 2>&1
			chmod --reference=${CFG_FILE} $CFG_FILE.$$ || exit 1 > /dev/null 2>&1
			mv -f $CFG_FILE.$$ ${CFG_FILE} > /dev/null 2>&1
	        fi
	fi
done

# and disable root user
/usr/sbin/usermod -L root

# do not execute some cron-jobs by default
for cron_job_dir in etc/cron.daily etc/cron.weekly etc/cron.monthly etc/cron.hourly; do
	for cron_job in `find $cron_job_dir -type f | grep -v "logrotate\|$cron_job_dir/\."`; do
		mv $cron_job $cron_job.disabled
	done
done

# Fill /etc/apt/sources.list
if [ ! -f etc/apt/sources.list ]; then

cat << EOF > etc/apt/sources.list
deb http://deb.debian.org/debian trixie main contrib non-free non-free-firmware
deb http://security.debian.org/debian-security trixie-security main contrib non-free non-free-firmware
deb http://deb.debian.org/debian trixie-updates main contrib non-free non-free-firmware

EOF

fi

# Disable bind9 ifup hook
for i in etc/network/if-down.d/bind9 etc/network/if-up.d/bind9; do
	mv $i $i.disabled
done

# Clean logs
for i in `find var/log/ -type f`; do
    echo "" > $i
done

# Remove /dev/log
rm -f dev/log >/dev/null 2>&1

# Fix modprobe.conf
touch etc/modprobe.conf

# Fix modules.dep
echo "#!/bin/sh
### BEGIN INIT INFO
# Provides:          modules_dep
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 6
# Short-Description: modules.dep creation.
# Description:       Create and destroy modules.dep.
### END INIT INFO

case \"\$1\" in
  start|\"\")
	if [ ! -d \"/lib/modules/\`uname -r\`\" ]; then
		mkdir -p /lib/modules/\`uname -r\`
	fi
	depmod -a >/dev/null 2>&1
	;;
  restart|reload|force-reload)
	echo \"Error: argument '\$1' not supported\" >&2
	exit 3
	;;
  stop|force-stop)
	if [ -d \"/lib/modules/\`uname -r\`\" ]; then
		rm -rf /lib/modules/\`uname -r\`
	fi
	;;
  *)
	echo \"Usage: modules_dep.sh [start|stop]\" >&2
	exit 3
	;;
esac

:

" > etc/init.d/modules_dep.sh
chmod a+x etc/init.d/modules_dep.sh
/usr/sbin/update-rc.d modules_dep.sh defaults >/dev/null 2>&1

# Create empty /etc/inittab file
touch etc/inittab

# Turn back wide-dhcpv6-client init script and clean default conf file
for i in etc/init.d/wide-dhcpv6-client; do
	mv -f $i.dpkg-dist $i
done
# regenerate dhcp6cctlkey if exists
cat > etc/default/wide-dhcpv6-client <<'EOFINITCONFFILE'
# Defaults for dhcpv6 client initscript
# Used by /etc/init.d/wide-dhcpv6-client

# Interfaces on which the client should send DHCPv6 requests and listen to
# answers. If empty, the client is deactivated.
INTERFACES=""
EOFINITCONFFILE

rm -f etc/wide-dhcpv6/dhcp6cctlkey

# Save /etc/rc.local copy (Debian 13 ships no default /etc/rc.local)
[ -f etc/rc.local ] && mv etc/rc.local etc/rc.local.orig

# PSBM-163931: firstboot rc.local - regenerate ssh host keys (ssh-keygen -A:
# modern default key types only; the old rsa1/dsa types were removed from
# OpenSSH) and the dhcp6 control key, then restore/remove itself and exit 0
# so rc-local.service does not end up failed.
echo "#!/bin/sh
rm -f /etc/ssh/ssh_host_*
/usr/bin/ssh-keygen -A
systemctl restart ssh 2>/dev/null

DHCP6CCTLKEY=/etc/wide-dhcpv6/dhcp6cctlkey
if [ -d /etc/wide-dhcpv6 ] && command -v uuencode >/dev/null 2>&1; then
	umask 066
	dd if=/dev/urandom bs=32 count=1 2>/dev/null | \
		uuencode -m \${DHCP6CCTLKEY} | head -n 2 | tail -n 1 > \${DHCP6CCTLKEY}
	umask 022
fi

if [ -f /etc/rc.local.orig ]; then
	mv -f /etc/rc.local.orig /etc/rc.local
else
	rm -f /etc/rc.local
fi
exit 0
" > etc/rc.local
chmod a+x etc/rc.local

# saslauthd tuning
CFG_FILE=etc/default/saslauthd
if [ -f $CFG_FILE ]; then
    sed -i -e "s/^THREADS=.*/THREADS=2/" -e "s/^START=.*/START=yes/" \
        $CFG_FILE
fi

apt-key update > /dev/null 2>&1

# Setup systemd as /sbin/init
rm -f sbin/init > /dev/null 2>&1
ln -s ../lib/systemd/systemd sbin/init > /dev/null 2>&1

# Mask services
# masked since #PSBM-145292
for s in systemd-resolved.service; do
        systemctl mask $s > /dev/null 2>&1
done

# Switch resolv.conf to old resolvconf-controlled scheme
rm -f etc/resolv.conf > /dev/null 2>&1
ln -s ../run/resolvconf/resolv.conf etc/resolv.conf > /dev/null 2>&1

# Create vzfifo service
cat >> lib/systemd/system/vzfifo.service << EOL
#  This file is part of systemd.
#
#  systemd is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.

[Unit]
Description=Tell that Container is started
ConditionPathExists=/proc/vz
ConditionPathExists=!/proc/bc
After=multi-user.target quotaon.service systemd-quotacheck.service

[Service]
Type=forking
ExecStart=/bin/touch /.vzfifo
TimeoutSec=0
RemainAfterExit=no

[Install]
WantedBy=multi-user.target
EOL

# PSBM-142706 / PSBM-164313: the ct-preset presets (cgroup accounting overrides
# from PSBM-142699, the ctpreset apt source, and the autoupgrade service+timer)
# are ALSO the conffiles of the ct-preset-deb package on repo.virtuozzo.com,
# which the weekly ct-preset-deb.timer runs "apt install ct-preset-deb" to pull
# preset updates. These files MUST be written byte-identical to that package's
# conffiles -- it is an alien-converted RPM whose files carry NO trailing newline
# -- otherwise the timer's apt install hits a dpkg conffile prompt, gets EOF and
# the service ends up failed. So use printf (no trailing newline); a heredoc
# would append one and break the md5 match. (lang=none also stops apt probing a
# non-existent Translation-en index on this flat repo -> 404 on every apt update.)
mkdir -p etc/apt/sources.list.d etc/systemd/system \
         etc/systemd/system.conf.d etc/systemd/user.conf.d \
         etc/systemd/system/user@.service.d etc/systemd/system/user-.slice.d

printf 'deb [trusted=yes lang=none] https://repo.virtuozzo.com/ctpreset/deb/ /' \
    > etc/apt/sources.list.d/ct-preset.list

printf '[Unit]\nDescription=Autoupgrade ct-presets\n[Service]\nType=oneshot\nExecStart=/usr/bin/apt install ct-preset-deb -y' \
    > etc/systemd/system/ct-preset-deb.service

printf '[Unit]\nDescription=Run ct-preset.service every monday at 00.00\n[Timer]\nOnCalendar=Mon *-*-* 01:00:00\nRandomizedDelaySec=2h\n[Install]\nWantedBy=timers.target' \
    > etc/systemd/system/ct-preset-deb.timer

# fix cgroups see #PSBM-142699
for i in system user; do
    printf '[Manager]\nDefaultCPUAccounting=no\nDefaultIOAccounting=no\nDefaultIPAccounting=no\nDefaultBlockIOAccounting=no\nDefaultMemoryAccounting=no\nDefaultTasksAccounting=no\nDefaultTasksMax=infinity' \
        > etc/systemd/${i}.conf.d/vz-override.conf
done
printf '[Service]\nDelegate=' > etc/systemd/system/user@.service.d/vz-override.conf
printf '[Slice]\nTasksMax=infinity' > etc/systemd/system/user-.slice.d/vz-override.conf


# Enable services
for service in vzfifo ct-preset-deb.timer; do
	systemctl enable $service > /dev/null 2>&1
done

rm -f etc/udev/disabled

cd $MYDIR > /dev/null
