#!/bin/bash
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Add noatime to the btrfs lines of an fstab, from Omarchy 4.6 (omarchy
# #20732). With the relatime default, the first read of a file after it
# changed, and a read a day later, writes the file's access time. On
# btrfs that write copies the inode's metadata block, and once a
# snapshot holds the old block the two are no longer shared: reading
# files grows the snapshots and writes to the SSD. noatime is a
# per-mount flag, so every btrfs line needs it, not only /. Mail
# readers that use atime for new mbox mail, and age-based cleanup of
# files that are read but never changed, see the modification time
# instead.
#
# A line that already names an access-time option (noatime, atime,
# relatime, strictatime and their no- forms) is left as it is: that is
# someone's choice. Comments, bind mounts and other file systems are
# left alone. Only the options field changes, so each line keeps its
# spacing. The file is written in place, keeping its owner, mode and
# SELinux label, and only when a line changed.
#
# Usage: atropos-fstab-noatime [FSTAB]     (default: /etc/fstab)

set -u
fstab=${1:-/etc/fstab}
[[ -f $fstab ]] || exit 0
tmp=$(mktemp) || exit 0
trap 'rm -f "$tmp"' EXIT

awk '
    function has_atime(opts,    n, o, i) {
        n = split(opts, o, ",")
        for (i = 1; i <= n; i++)
            if (o[i] ~ /^(no)?(rel|strict)?atime$/)
                return 1
        return 0
    }
    $0 ~ /^[[:space:]]*#/ || $3 != "btrfs" { print; next }
    NF == 3 { print $0 " noatime"; changed++; next }
    has_atime($4) { print; next }
    match($0, /^[[:space:]]*[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+[^[:space:]]+/) {
        # RLENGTH ends at the last character of the options field
        print substr($0, 1, RLENGTH) ",noatime" substr($0, RLENGTH + 1)
        changed++
        next
    }
    { print }
    END { exit changed ? 0 : 3 }
' "$fstab" > "$tmp"
rc=$?
# 3: no btrfs line needed it. Anything else but 0 is an awk failure.
((rc == 0)) || exit 0
# Never shorten the file: the same number of lines, or nothing is written
[[ $(awk 'END { print NR }' "$tmp") == "$(awk 'END { print NR }' "$fstab")" ]] || exit 0
cat "$tmp" > "$fstab" || exit 0
echo "atropos-fstab-noatime: added noatime to the btrfs mounts in $fstab"
exit 0
