#!/bin/bash
set -e

ROOT=/media/root-ro
CONF=$ROOT/etc/systemd/system/apt-update.service
TIMER=$ROOT/etc/systemd/system/apt-update.timer
UPDATE_SCRIPT=/media/flash/update_apt.sh

REPO=$ROOT/etc/apt/sources.list.d/repo-lula.list
QTR70_CONF="/media/flash/qtr70.conf"

# Check if Lula already is installed.
if dpkg -s lula >/dev/null 2>&1; then
    exit 0
fi


ROOT_RW=0

cleanup() {
    set +e

    echo "Cleaning up..."

    for m in media/flash run sys proc dev; do
        if mountpoint -q "$ROOT/$m"; then
            umount "$ROOT/$m"
        fi
    done

    sync

    if [ "$ROOT_RW" -eq 1 ]; then
        echo "Re-locking root filesystem..."
        mount -o remount,ro "$ROOT"
    fi
}

trap cleanup EXIT

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

ROOT_RW=1

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

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

# Need to mount /media/flash so the postinst script can write to qtr70.conf.
mkdir -p $ROOT/media/flash
mount --bind /media/flash $ROOT/media/flash

echo "Installing Lula for QTR-70 from apt"
chroot $ROOT /bin/bash -c "
    apt update
    apt install -y qtr70-lula
    apt clean
"

if [ ! -e $CONF ]; then

    if [ ! -e $UPDATE_SCRIPT ]; then
        cat <<'EOF' > "$UPDATE_SCRIPT"
#!/bin/bash

AUTOMATIC_UPDATES_ENABLED=$(awk -F= '/^AUTOMATIC_UPDATES=/ {print $2}' /media/flash/qtr70.conf)

if [ "${AUTOMATIC_UPDATES_ENABLED:-0}" -eq 0 ]; then
    exit
fi

apt update

REPO_SCRIPT_VERSION=$(apt-cache policy qtr-70-scripts | awk '/Candidate:/ {print $2}')
DEPLOYED_SCRIPT_VERSION=$(awk -F= '/^SCRIPT_VERSION=/ {print $2}' /media/flash/qtr70.conf)

if [ "$REPO_SCRIPT_VERSION" != "$DEPLOYED_SCRIPT_VERSION" ]; then
    apt install -y qtr-70-scripts
fi

REPO_LULA_VERSION=$(apt-cache policy qtr70-lula | awk '/Candidate:/ {print $2}')
DEPLOYED_LULA_VERSION=$(awk -F= '/^LULA_VERSION=/ {print $2}' /media/flash/qtr70.conf)

if [ "$REPO_LULA_VERSION" != "$DEPLOYED_LULA_VERSION" ]; then
    apt install -y qtr70-lula
fi
EOF

        chmod +x /media/flash/update_apt.sh
    fi

    cat <<EOF > "$CONF"
[Unit]
Description=Run daily apt updates to check if new version of packages are available

[Service]
Type=oneshot
ExecStart=/media/flash/update_apt.sh

# Optional:
User=root
WorkingDirectory=/media/flash/

# Good practice
StandardOutput=journal
StandardError=journal
EOF


    cat <<EOF > "$TIMER"
[Unit]
Description=Run apt update script daily around 05:00 with random delay

[Timer]
OnCalendar=*-*-* 05:00:00
RandomizedDelaySec=30m
Persistent=true

[Install]
WantedBy=timers.target
EOF

    # Enable apt-update timer, no need for daemon reload as that will be handled
    # by reboot
    chroot "$ROOT" systemctl enable apt-update.timer
fi


# 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

 # Enable the lula services needed to run lula.
mkdir -p $ROOT/etc/systemd/system/multi-user.target.wants

cp /media/flash/lula-utils/lula.service  $ROOT/etc/systemd/system/lula.service
cp /media/flash/lula-utils/slave_system.service  $ROOT/etc/systemd/system/slave_system.service

ln -sf  $ROOT/etc/systemd/system/lula.service \
    $ROOT/etc/systemd/system/multi-user.target.wants/lula.service

ln -sf  $ROOT/etc/systemd/system/slave_system.service \
    $ROOT/etc/systemd/system/multi-user.target.wants/slave_system.service

sync
sleep 2

echo "Done, rebooting!"
sleep 2
systemctl reboot
