#!/bin/sh /etc/rc.common
# Copyright (C) 2008-2011 OpenWrt.org

START=50
STOP=10

USE_PROCD=1

validate_section_hdidle()
{
	uci_validate_section hd-idle hd-idle "${1}" \
		'disk:string' \
		'enabled:bool' \
		'idle_time_interval:uinteger:10' \
		'idle_time_unit:string:minutes'
}

compute_seconds() {
	local interval="$1"
	local unit="$2"

	# compute interval in seconds
	case "$unit" in
		"days" )
			interval_seconds=$(($interval*60*60*24))
			;;
		"hours" )
			interval_seconds=$(($interval*60*60))
			;;
		"minutes" )
			interval_seconds=$(($interval*60))
			;;
		"seconds" )
			interval_seconds=$interval
			;;
		* )
			# default is minutes
			interval_seconds=$(($interval*60))
			;;
	esac

	echo $interval_seconds
}

hdidle_append() {
	local disk enabled idle_time_interval idle_time_unit

	validate_section_hdidle "${1}" || return

	[ "$enabled" -gt 0 ] || return

	if [ "$numdisks" = "0" ]; then
		procd_open_instance
		procd_set_param command /usr/bin/hd-idle
		procd_append_param command -d -i 0
	fi
	procd_append_param command -a $disk
	procd_append_param command -i "$(compute_seconds $idle_time_interval $idle_time_unit)"
	numdisks=$(( numdisks + 1 ))
}

start_service() {
	config_load "hd-idle"

	numdisks="0"
	config_foreach hdidle_append "hd-idle"

	if [ "$numdisks" -gt 0 ]; then
		procd_set_param respawn
		procd_close_instance
	fi
}
