#!/bin/sh -e

# Copyright (C) 2022 UBports Foundation.
# SPDX-License-Identifier: GPL-3.0-or-later

log() {
    echo "$*" >&2
}

# The purpose of this script is to make sure that `/usr/share/session-migration/
# scripts` has a sane mtime, taking mtime of all files inside it into account.
# See: https://gitlab.com/ubports/development/core/focal-projectmanagement-missing-packages/-/issues/81

dir="/usr/share/session-migration/scripts"
dir_mtime=$(stat -c "%Y" ${dir})
# Awk code from: https://stackoverflow.com/a/11931715
files_max_mtime=$(stat -c "%Y" ${dir}/* | awk '$0 > x { x=$0 }; END { print x }')

if [ "$files_max_mtime" -le "$dir_mtime" ]; then
    log "Workaround not needed. Script directory already have sensible mtime."
    exit 0
fi

if ! grep -q overlay /proc/filesystems; then
    log "Workaround needed, but system doesn't have overlayfs. Configure kernel, or" \
        "report back if your kernel is <= 3.18"
    exit 1
fi

# The trick here is that, overlayfs will take the mtime from the top-most dir,
# so we put the original dir at the bottom, and then put an empty directory
# on top just to alter the directory's apparent mtime.

tmp_dir=$(mktemp -d /tmp/workaround-session-migration-mtime.XXXXXX)
chmod 444 "${tmp_dir}" # Just to be safe
touch --date="@${files_max_mtime}" "$tmp_dir"

mount -t overlay \
    -o lowerdir="${tmp_dir}:${dir}" \
    workaround-session-migration-mtime \
    "$dir"

log "Mounted overlay of session-migration script dir to workaround bogus mtime."
