#!/bin/bash
set -e

ROOT=/media/root-ro
CONF=$ROOT/etc/apt/apt.conf.d/50unattended-upgrades
REPO=$ROOT/etc/apt/sources.list.d/repo-qtr70-scripts.list
QTR70_CONF="/media/flash/qtr70.conf"

echo "Unlocking root filesystem..."
mount -o remount,rw $ROOT

echo "deb [trusted=yes] http://apt.qt-systems.se qtr70 main" | sudo tee $REPO

echo "Binding system directories..."
mount --bind /dev $ROOT/dev
mount --bind /proc $ROOT/proc
mount --bind /sys $ROOT/sys

echo "Entering chroot and installing unattended-upgrades..."
chroot $ROOT /bin/bash -c "
    apt update
    apt install -y unattended-upgrades
"

if ! grep -q 'suite=./,package=qtr-70-scripts' "$CONF"; then
    cat <<EOF >> "$CONF"

Unattended-Upgrade::Origins-Pattern {
    "suite=./,package=qtr-70-scripts";
};
EOF
fi

# Create the condition script inside the chroot
cat <<'EOF' > $ROOT/usr/local/bin/apt-guard.sh
#!/bin/bash
# Load config file
. /media/flash/qtr70.conf &>/dev/null

# Put output of the rest of this script into a log file
exec > /var/log/qtr70.log

if [ "$AUTOMATIC_UPDATES" -eq 0 ]; then
    echo "$(date +%Y-%m-%d\ %H:%M:%S) - apt-guard.sh Disabling apt-daily services"

    systemctl stop apt-daily.timer apt-daily.service
    systemctl stop apt-daily-upgrade.timer apt-daily-upgrade.service
    systemctl mask apt-daily.timer apt-daily.service
    systemctl mask apt-daily-upgrade.timer apt-daily-upgrade.service
fi
EOF

chmod +x $ROOT/usr/local/bin/apt-guard.sh

# Create the systemd service inside the chroot
cat <<'EOF' > $ROOT/etc/systemd/system/apt-guard.service
[Unit]
Description=Disable apt timers if configured
RequiresMountsFor=/media/flash
Before=apt-daily.service apt-daily.timer apt-daily-upgrade.service apt-daily-upgrade.timer

[Service]
Type=oneshot
ExecStart=/usr/local/bin/apt-guard.sh

[Install]
WantedBy=multi-user.target
EOF

# Enable the service inside the chroot
chroot $ROOT /bin/bash -c "systemctl daemon-reload && systemctl enable apt-guard.service"

echo "Cleaning up..."
umount $ROOT/dev
umount $ROOT/proc
umount $ROOT/sys

echo "Installing QTR-70 scripts from apt"
apt update
apt install -y qtr-70-scripts

# Exit if AUTOMATIC_UPDATES already exists
if grep -q '^AUTOMATIC_UPDATES=' "$QTR70_CONF"; then
    echo "AUTOMATIC_UPDATES already set, skipping."
else
    # Insert AUTOMATIC_UPDATES=1 after the line [SW]
    sed -i '/^\[SW\]/a AUTOMATIC_UPDATES=1' "$QTR70_CONF"

    echo "Setting AUTOMATIC_UPDATES=1 in QTR70 config."
fi

echo "Re-locking root filesystem..."
mount -o remount,ro $ROOT

echo "Done, rebooting!"
(sh -c 'sync; sleep 2; systemctl reboot') &
