#!/bin/sh
##############################################################################
#
#  Copyright (c) 2005, Doremi Labs, Inc.
#    All rights reserved.
#
#  Redistribution in source or binary forms, with or without
#  modification, are NOT permitted.
#
#    Doremi Labs, Inc.
#    1020 Chestnut St.
#    Burbank, CA 91506
#    Tel : (818) 562 1101
#    Fax : (818) 562 1109
#
##############################################################################

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/doremi/bin:/doremi/sbin

trap "" 1 15

v_platform="dcp2000"

if [ -e /etc/platform ]; then
  v_platform=$(cat /etc/platform | tr -d '-')
fi

#
#  Initialize default color
#    Partially based on old Red-Hat 5 scripts.
#
BOOTUP=color
if [ -x /usr/bin/tput ] ; then
	RES_COL=$( /usr/bin/tput cols )
else
	RES_COL=80
fi
RES_COL=$( expr $RES_COL - 10 )
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

RAIDSTANDBYALARM="/tmp/alarms/RAID_standby"

#
#  standby_boot_sequence( )
#  
#    Checks if we are booting in standby mode.
#
# 
standby_boot_sequence()
{
	test -e "$RAIDSTANDBYALARM" && return 0
	return 1
}

#
#  lockfile( lock_filename )
#  
#    Create the lock file `lock_filename'.
#
# 
lockfile()
{
	local filename=$1
	local _dirname=$( dirname "${filename}" )
	if [ ! -e "${_dirname}" ]; then 
		install -m 0755 -o root -g root -d "${_dirname}"
	fi
	touch "${filename}"
}

#
#  start_daemon( daemon-name, arg1, argN, ... )
#
#    Start daemon 'daemon-name' with arguments 'arg1', 'argN'.
#
#    ENVIRONMENT VARIABLE:
#      $LOCKFILE - Create the file "LOCKFILE" if the daemon has successfully
#                  started.
#
start_daemon()
{
	local program="$1"
	shift 1
	start-stop-daemon --quiet --start --exec $program -- "$@" > /dev/null 2>&1 
	if [ $? -eq 0 ] ; then
		[ "$LOCKFILE" != "" ] && lockfile "$LOCKFILE"
		echo_success
	else
		echo_failure
	fi
}

#
#  stop_daemon_static( daemon-name, retry )
#
#    Stop daemon 'daemon-name' by sending the TERM (15) signal. If it does not
#    within 'retry' seconds, the process is killed with KILL (9) signal.
#    
#    ENVIRONMENT VARIABLE:
#      $LOCKFILE - Delete the file "LOCKFILE" if the daemon has successfully
#                  stopped
#
stop_daemon_static()
{
	local PROGRAM="$1"
	local RETRY="$2"
	shift 1

	start-stop-daemon --quiet --stop --retry ${RETRY} --exec ${PROGRAM} > /dev/null 2>&1 
	if [ $? -eq 0 ] ; then
		echo_success
	else
		echo_failure
	fi
	[ "$LOCKFILE" != "" ] && rm -f "$LOCKFILE"
}

#
# stop_daemon( daemon-name )
#
#    Call function 'stop_daemon_static' with retry of 30s.
#
stop_daemon()
{
	local PROGRAM="$1"

	stop_daemon_static "${PROGRAM}" 30
}

#
#  stop_daemon_background( daemon-name )
#
#    Call function 'stop_daemon_static' in background. 
#
stop_daemon_background()
{
        local PROGRAM="$1"
        local RETRY_DELAY=14

	# Override default RETRY_DELAY value, if STANDBY_DELAY is exported
	[ "${STANDBY_DELAY}" != "" ] && RETRY_DELAY=${STANDBY_DELAY}

	stop_daemon_static "${PROGRAM}" ${RETRY_DELAY} > /dev/null &
}

#
#  echo_success()
#    Display [   OK   ] at this end of the cursor line.
#
echo_success() 
{
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $MOVE_TO_COL
	echo -n "[  "
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $SETCOLOR_SUCCESS
	echo -n $"OK"
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $SETCOLOR_NORMAL
	echo -n "  ]"
	echo -ne "\r"
	return 0
}

#
#  echo_failure()
#    Display [ FAILED ] at this end of the cursor line.
#
echo_failure() 
{
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $MOVE_TO_COL
	echo -n "["
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $SETCOLOR_FAILURE
	echo -n $"FAILED"
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $SETCOLOR_NORMAL
	echo -n "]"
	echo -ne "\r"
	return 1
}

#
#  echo_warning()
#    Display [ WARNG  ] at this end of the cursor line.
#
echo_warning() 
{
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $MOVE_TO_COL
	echo -n "["
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $SETCOLOR_WARNING
	echo -n $"WARNG "
	[ "$BOOTUP" = "color" ] && [ "${COLOR_DISABLED}" != "1" ] && $SETCOLOR_NORMAL
	echo -n "]"
	echo -ne "\r"
	return 1
}

#
#
#
SQLITE="/doremi/sbin/sqlite3"

#
#  sqlite_database_integrity_check()
#    Use the SQLite PRAGMA integrity_check call to check the 
#    database integrity.
#    $1: path to database file
#
sqlite_database_integrity_check()
{
	test $# -eq 1 || return 22
	
	local path=$1
	echo "PRAGMA integrity_check;" | ${SQLITE} "${path}" 2>&1 | grep -q -w 'ok\|locked' 
}

#
#  sqlite_database_integrity_check_ext()
#    Use the SQLite PRAGMA integrity_check call to check the 
#    database integrity.
#    Also checks the output logs to determine other possible corruptions
#    $1: path to database file
#
sqlite_database_integrity_check_ext()
{
	local res
	local tmpres
	
	tmpres=$(sqlite_database_integrity_check $1)
	res=$?
	if [ $res == 0 ]; then
		if echo $tmpres | grep -q "missing from overflow list"; then
			res=1
		fi
	fi
	return $res
}

#
#  sqlite_database_fixup()
#    Fix a corrupted SQLite database by dumping the DB 
#    and re-create it.
#    $1: path to database file
#    $2: temp working folder (optional)
#    If a failure occurs, the original corrupted database
#    is restored. It is the caller responsability to 
#    delete the corrupted database.
#
sqlite_database_fixup()
{
	test $# -ge 1 || return 22
	
	local osdb=$1
	local temp=$2
	# default to /tmp if parameter is missing
	if [ "$temp" = "" ]; then
		temp="/tmp"
	fi
	local psql="${temp}/$( basename ${osdb} ).sql"
	local nsdb="${temp}/$( basename ${osdb} )"
	echo ".dump" | ${SQLITE} "${osdb}" > "${psql}"
	if [ $? -ne 0 ]; then
		rm -f "${psql}"
		return 1
	fi
	echo ".quit" | ${SQLITE} -init "${psql}" "${nsdb}"
	if [ $? -ne 0 ]; then
		rm -f "${psql}"
		rm -f "${nsdb}"
		return 2
	fi
	rm -f "${psql}"
	mv -f "${nsdb}" "${osdb}"
	return 0
}

#
#  sqlite_database_fixup_strerror()
#    Return a string version of the error code returned
#    by sqlite_database_fixup()
#    $1: error code
#
sqlite_database_fixup_strerror()
{
	test $# -eq 1 || return 22
	case "$1" in
		0) echo "Success"
			;;
		1) echo "Could not dump database"
			;;
		2) echo "Could not create new database"
			;;
		*) echo "Unknown"
			;;
	esac
}

#
#  ver2num()
#    Convert Doremi version number to a long int value.
#
ver2num()
{
	echo "$1" | awk -F '[^0-9]+' '{print $1*256*65536+$2*65536+$3*256+$4}'
}

#
#  set_readonly_fs_to_readwrite()
#    Remount all read-only filesystem to read-write
#
set_readonly_fs_to_readwrite()
{
	mount -o rw,remount /
	mount -o rw,remount /boot
}

#
#  restore_readonly_fs()
#    Remount all orignal read-only to read-only
#
restore_readonly_fs()
{
	mount -o ro,remount /
	mount -o ro,remount /boot
}

#
#  check_single_instance()
#    returns 1 if the provided lockfile exists
#      and the process id inside the lockfile matches a running process
#    else returns 0 and updates lockfile with caller process id
#    $1: lockfile basename identifying running instance
#
check_single_instance()
{
	local lockfile=$1
	
	if [ -e $lockfile ] && ps -p $(cat $lockfile) > /dev/null; then
		return 1
	fi
	
	mkdir -p $(dirname $lockfile)
	echo -n $$ > $lockfile
	return 0
}

