#!/bin/bash
# Copyright (c) [2018-2020] SUSE LLC
#
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, contact SUSE LLC.
#
# To contact SUSE LLC about this file by physical or electronic mail, you may
# find current contact information at www.suse.com.

# This script can mask or unmask systemd mount and swap units since systemd
# and YaST mounting the same file system leads to race conditions (see bsc
# #1073633). Unfortunately there is no single systemctl command to mask those
# units - so each must be masked individually.

# Since it is unclear how to identify mount and swap units generated by the
# systemd-gpt-auto-generator (see bsc #1073633 comment #79) this script
# masks/unmasks almost all mount and swap units.

# Error messages about non-existing units may be wrong (see bsc #1095973).


query_units()
{
    /usr/bin/systemctl list-units --full --all --type mount,swap --no-legend --plain | while read -r unit dummy ; do

	# skip root and sysroot
	if [[ $unit == -.mount || $unit == sysroot.mount ]] ; then
	   continue
	fi

	# skip mount points below /dev, /run, /proc and /sys since these are
	# usually not on block devices (e.g. dev-hugepages.mount) and masking
	# them could maybe lead to problems
	if [[ $unit == dev-*.mount || $unit == run-*.mount || $unit == proc-*.mount ||
	      $unit == sys-*.mount ]] ; then
	   continue
	fi

	echo "$unit"

    done
}


mask_units()
{
    query_units | /usr/bin/xargs --verbose --no-run-if-empty --delimiter='\n' /usr/bin/systemctl --runtime $1 --
}


usage()
{
    echo "Usage: $0 --mask/--unmask" 1>&2
    exit 1
}


case "$1" in

    --mask)
	mask_units mask
	;;

    --unmask)
	mask_units unmask
	;;

    *)
	usage
	;;

esac
