# Copyright (c) 2004-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header$

# Contributed by Roy Marples (uberlord@gentoo.org)

# int netmask2cidr(char *netmask)
#
# Returns the CIDR of a given netmask
netmask2cidr() {
	local binary="" i bin

	for i in ${1//./ }; do
		bin=""
		while [[ ${i} != 0 ]]; do
			bin=$[${i}%2]${bin}
			(( i=i>>1 ))
		done
		binary="${binary}${bin}"
	done
	binary=${binary%%0*}
	echo ${#binary}
}

# char* netmask2cidr(int cidr)
#
# Returns the netmask of a given CIDR
cidr2netmask() {
	local cidr=${1} netmask="" done=0 i sum=0 cur=128
	local octets frac

	(( octets=cidr/8 ))
	(( frac=cidr%8 ))
	while [[ octets -gt 0 ]]; do
		netmask="${netmask}.255"
		(( octets-- ))
		(( done++ ))
	done

	if [[ ${done} -lt 4 ]]; then
		for (( i=0; i<${frac}; i++ )); do
			(( sum+=cur ))
			(( cur/=2 ))
		done
		netmask="${netmask}.${sum}"
		(( done++ ))
		
		while [[ ${done} -lt 4 ]]; do
			netmask="${netmask}.0"
			(( done++ ))
		done
	fi

	echo ${netmask:1}
}

# char* interface_device(char *iface)
#
# Gets the base device of the interface
# Can handle eth0:1 and eth0.1
# Which returns eth0 in this case
interface_device() {
	local dev=${1%%.*}
	[[ ${dev} == ${1} ]] && dev=${1%%:*}
	echo ${dev}
}

# char* interface_type(char* iface)
#
# Returns the base type of the interface
# eth, ippp, etc
interface_type() {
	echo ${1%%[0-9]*}
}

# char* interface_variable(char *iface)
#
# Returns a bash variable name based on the interface
interface_variable() {
	LC_ALL=C echo ${1//[![:word:]]/_}
}

# bool clean_pidfile(char *file)
#
# Removes the given pidfile if the process is not running
# Returns 1 if the process is still running otherwise 0
clean_pidfile() {
	local pidfile=${1}

	[[ ! -f ${pidfile} ]] && return 0
	local pid=$( cat ${pidfile} )

	if [[ -n ${pid} ]]; then
		local cmd=${pidfile##*/}
		cmd=${cmd%%-*}
		ps -p ${pid} 2>/dev/null | grep -q ${cmd} && return 1
	fi

	rm -f ${pidfile}
	return 0
}

# bool process_finished(int pid, char* cmd)
#
# We wait for 10 seconds until the command ${cmd}
# stops running on the process ${pid}
process_finished() {
	local i pid=${1} cmd=${2} secs=${3:-9}

	for (( i=0; i<secs; i++ )); do
		ps -p ${pid} | grep -q ${cmd} || return 0
		sleep 1
	done

	return 1
}
