#!/bin/bash
# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# ex: ts=8 sw=4 sts=4 et filetype=sh

# This script adds a drop-in which disables systemd-fsck for the /usr
# partition. Cases:
#
# 1. /usr is backed by dm-verity and is read-only. fsck.ext4 would fail
#    and print a confusing error to the journal.
#
# 2. The /usr filesystem is configured for verity but the bootloader is
#    too old to enable it. fsck.ext4 would fail because of the read-only
#    compat flags that prevent writing to the filesystem, and print a
#    confusing error to the journal.
#
# 3. Neither #1 or #2 are true because this is a dev image. This case
#    is not trivial to detect and not actually important.

set -e

UNIT_DIR="${1:-/tmp}"

# env var for testing
if [[ -n "${USR_FSCK_GENERATOR_CMDLINE}" ]]; then
    cmdline=( ${USR_FSCK_GENERATOR_CMDLINE} )
else
    cmdline=( $(</proc/cmdline) )
fi

# Usage: cmdline_arg name default_value
cmdline_arg() {
    local name="$1" value="$2"
    for arg in "${cmdline[@]}"; do
        if [[ "${arg%%=*}" == "${name}" ]]; then
            value="${arg#*=}"
        fi
    done
    echo "${value}"
}

usr=$(cmdline_arg mount.usr)
if [[ -z "$usr" ]]; then
    usr=$(cmdline_arg usr)
fi

case "${usr}" in
    LABEL=*)
        usr="$(echo $usr | sed 's,/,\\x2f,g')"
        usr="/dev/disk/by-label/${usr#LABEL=}"
        ;;
    UUID=*)
        usr="${usr#UUID=}"
        usr="$(echo $usr | tr "[:upper:]" "[:lower:]")"
        usr="/dev/disk/by-uuid/${usr}"
        ;;
    PARTUUID=*)
        usr="${usr#PARTUUID=}"
        usr="$(echo $usr | tr "[:upper:]" "[:lower:]")"
        usr="/dev/disk/by-partuuid/${usr}"
        ;;
    PARTLABEL=*)
        usr="/dev/disk/by-partlabel/${usr#PARTLABEL=}"
        ;;
esac

# Only proceed if the source is a path.
if [[ "${usr}" != /* ]]; then
    exit 0
fi

usr="$(systemd-escape -p "${usr}")"

dropin_dir="${UNIT_DIR}/systemd-fsck@${usr}.service.d"
mkdir -p "${dropin_dir}"
cat >"${dropin_dir}/disable.conf" <<EOF
# Automatically generated by usr-fsck-generator

[Unit]
ConditionPathIsDirectory=/dev/null
EOF
