#!/usr/bin/bash

# This file must contain all required operations to fix/update any issue
# of the data partition.

# This script is called by systemd as an oneshot service just after the
# filesystem be mounted. However, it should execute the operations only
# once after a system upgrade.

# All code found here must be kept for long-life term or even forever and
# must always contain, at least, the following information: title, version
# it was added and reason why it was added (description).

# mount /data in tmpfs if unavailable
if [ ! -w /data/ ] && (! /usr/bin/mount | /usr/bin/grep /data | /usr/bin/grep -q -e ext4 -e ubifs); then
    /usr/bin/mount -t tmpfs -o defaults,noatime,mode=1777 tmpfs /data
fi

# mount /root in tmpfs if unavailable
if [ ! -w /root/ ] && (! /usr/bin/mount | /usr/bin/grep -q /root); then
    /usr/bin/mount -t tmpfs -o defaults,noatime,mode=1777 tmpfs /root
    # let others know of what we did...
    /usr/bin/touch /tmp/root-mounted-tmpfs
fi

# make sure /data is writable by HMI user.
# forced-install updates can retain the same version, but install new contents of user data,
# without this, it is impossible to save alsamixer state, the error being:
# /usr/sbin/alsactl: save_state:1635: Cannot open /data/asound.state for writing: Permission denied
/usr/bin/chmod 777 /data/

# check if it's a new version
if [[ -f /data/.last-data-operation ]]; then
    DATA_OP=$(/usr/bin/cat /data/.last-data-operation | /usr/bin/cut -d'.' -f1-3)
    RELEASE=$(/usr/bin/cat /etc/mod-release/release | /usr/bin/cut -d'.' -f1-3)
    LATEST=$(/usr/bin/echo -e "${DATA_OP}\n${RELEASE}" | /usr/bin/sort -t. -k 1,1n -k 2,2n -k 3,3n | /usr/bin/tail -n1)

    if [[ "${LATEST}" == "${DATA_OP}" ]]; then
        exit 0
    fi
fi

# title: remove old authorized_keys
# added: v1.1.0
# description: Since this version ssh access via password is allowed again.
# The authorized_keys should not contain any old access key.
if [[ -f /root/.ssh/authorized_keys ]]; then
    /usr/bin/sed -i '/user@mod/d' /root/.ssh/authorized_keys
fi

# update last data operation
/usr/bin/cp /etc/mod-release/release /data/.last-data-operation
exit 0
