#!/bin/sh -e

##########################################################################
#   Script description:
#       Turn soft updates journal on or off on all UFS filesystems
#       
#   History:
#   Date        Name        Modification
#   2020-05-23  Jason Bacon Begin
##########################################################################

usage()
{
    printf "Usage: $0 on|off\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ $# != 1 ]; then
    usage
fi

case $(auto-ostype) in
FreeBSD)
    case $1 in
    on)
	state=enable
	;;
    off)
	state=disable
	;;
    *)
	usage
	;;
    esac
    
    for fs in $(awk '$3 == "ufs" { print $1 }' /etc/fstab); do
	mount_opts="$(mount -t ufs | awk -v fs=$fs '$1 == fs { print $0 }')"
	if [ 0"$mount_opts" != 0 ] && ! echo $mount_opts | fgrep read-only; then
	    cat << EOM
$fs is mounted with write enabled, cannot tune it.
Reboot to single-user mode and try again.

EOM
	    exit 1
	else
	    printf "Tuning $fs...\n"
	    tunefs -j $state $fs
	fi
    done
    printf "Changes will not take effect until the system is rebooted.\n"
    printf "Reboot now? [y]/n "
    read reboot
    if [ 0$reboot != 0n ]; then
	shutdown -r now
    fi
    ;;

*)
    auto-unsupported-os $0
    printf "$0: Only applicable on FreeBSD.\n"
    exit 1
    ;;

esac
