#!/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
    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 [ -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
	    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
for fs in $rc_list; do
    tunefs -j $state \$fs
    mount -u -o rw /
    rm -f $rc_file
done
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
