#!/bin/sh
# $NetBSD$

# BEFORE: fsck

$_rc_subr_loaded . /etc/rc.subr

name="drivecache"
rcvar=$name
start_cmd="drivecache_start"
stop_cmd=":"

# Options:
# Set drivecache_flags to OFF to force write caches off
# Set drivecache_list to list of drives to alter

check_dup()
{
       local item search
       item="$1"
       shift
       for search in $*
       do
               [ "$item" = "$search" ] && return 1
       done
       return 0
}

drivecache_start()
{
       # We are running before mount_critlocal, so we might not have access
       # to /usr for awk, sed, grep, etc.
       case "$drivecache_flags" in
       [oO][fF][fF])
               action="disabled"
               cachetype="r"
               ;;
       *)
               action="enabled"
               cachetype="rw"
               ;;
       esac

       disk_action=""
       disk_noaction=""
       disk_nocache=""
       if [ -z "$drivecache_list" ]; then
               drivecache_list="sd* wd*"
       fi

       list=""
       for atom in $drivecache_list
       do
               for disk in  $(/sbin/sysctl -n hw.disknames)
               do
                       case "$disk" in
                       $atom)
                               if check_dup "$disk" $list; then
                                       list="$list${list:+ }$disk"
                               fi
                               ;;
                       esac
               done
       done

       for disk in $list
       do
               current=$(dkctl $disk getcache)
               enabled="n"
               case "$current" in
               *"write-back cache enabled"*)
                       enabled="y"
                       ;;
               esac
               # Skip if no change
               if [ "$enabled" = y -a "$action" = enabled ]; then
                       disk_noaction="${disk_noaction} $disk"
                       continue
               fi
               if [ "$enabled" = n -a "$action" = disabled ]; then
                       disk_noaction="${disk_noaction} $disk"
                       continue
               fi

               # Check cache setting is changeable
               case "$current" in
               *"write cache enable is changeable"*)
                       disk_action="${disk_action} $disk"
                       dkctl $disk setcache $cachetype
                       ;;
               *)
                       disk_nocache="${disk_nocache} $disk"
                       ;;
               esac
       done
       if [ -n "$disk_noaction" ]; then
               echo "Write-cache already $action on:$disk_noaction"
       fi
       if [ -n "$disk_action" ]; then
               echo "Write-cache force $action on:$disk_action"
       fi
       if [ -n "$disk_nocache" ]; then
               echo "Write-cache cannot be $action on:$disk_nocache"
       fi
}

load_rc_config $name
run_rc_command "$1"