#!/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 fs [fs ...]\n"
    printf "       $0 on|off all\n"
    exit 1
}


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

if [ $# -lt 2 ]; then
    usage
fi

case $(auto-ostype) in
FreeBSD)
    case $1 in
    on)
	state=enable
	;;
    off)
	state=disable
	;;
    *)
	usage
	;;
    esac
    shift
    
    if [ $1 = all ]; then
	fs_list=$(awk '$3 == "ufs" { print $1 }' /etc/fstab)
    else
	fs_list="$@"
    fi

    # Cannot use /usr/local/etc as it may not be mounted yet
    rc_dir=/etc/rc.local_early.d
    mkdir -p $rc_dir
    rc_file=$rc_dir/auto-su+j-toggle.sh
    cp -f /usr/local/share/auto-admin/local_early /etc/rc.d
    cp -f /usr/local/share/auto-admin/rc.local_early /etc
    
    echo "fs list = " $fs_list
    df
    
    for fs in $fs_list; do
	printf "Checking $fs...\n"
	mount_opts="$(mount -t ufs | awk -v fs=$fs '($1 == fs) || ($3 == fs) { print $0 }')"
	echo $mount_opts
	
	# If old .sujournal exists, tunefs will refuse to enable su+j
	if [ $state = enable ] && [ -n "$mount_opts" ] && ! echo $mount_opts | fgrep journal; then
	    if echo $fs | grep -q '/dev'; then
		mount_point=$(awk -v dev=\$fs '\$1 == dev { print \$2 }' /etc/fstab)
	    else
		mount_point=$fs
	    fi
	    rm -f $mount_point/.sujournal
	fi
	
	# If fs is read-only, tune it now
	if [ -n "$mount_opts" ] && ! echo $mount_opts | fgrep read-only; then
	    cat << EOM

$fs is mounted with write enabled, cannot tune it.  
Scheduling change for next reboot.

EOM
	    rc_list="$rc_list $fs"
	else
	    # If rw, schedule tuning for single-user mode of next reboot
	    printf "Tuning $fs...\n"
	    tunefs -j $state $fs
	fi
    done
    
    if [ ! -z "$rc_list" ]; then
	cat << EOM > $rc_file
#!/bin/sh

# $rc_file

printf "Toggling soft-updates journals.  System will reboot automatically.\n"
sleep 2
set -x
for fs in $rc_list; do
    tunefs -j $state \$fs
done
mount -u -o rw /
rm -f $rc_file
reboot
EOM
    else
	rm -f $rc_file
    fi
    
    printf "Changes will not take effect until the next mount of each FS.\n"
    printf "Either unmount and remount each FS, or reboot the system.\n"
    printf "Reboot now? y/[n] "
    read reboot
    if [ 0$reboot = 0y ]; then
	shutdown -r now
    fi
    ;;

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

esac
