#!/bin/sh
#
# chkconfig: 2345 92 8
# description: dCache init script

# Solaris doesn't have a POSIX compliant shell as /bin/sh. We
# try to find one and execute it.
if [ "$1" = "%" ]; then
    shift
elif [ "`uname`" = "SunOS" ]; then
    if [ -x /usr/xpg4/bin/sh ]; then
        exec /usr/xpg4/bin/sh $0 % $*
    elif [ -x /bin/bash ]; then
        exec /bin/bash $0 % $*
    else
        echo "Cannot find POSIX compliant shell. This script will"
        echo "probably break, but we attempt to execute it anyway."
    fi
fi

# Prints help screen and exits with error status 2
usage()
{
    echo "Usage: $(basename $0) [OPTION]... COMMAND"
    echo
    echo "Valid options are:"
    echo "   -d=<path to dcache installation>   default is /opt/d-cache"
    echo
    echo "Valid commands are:"
    echo "   condrestart [<domain or service> ...]"
    echo "   dump heap [--force] <domain> <file>"
    echo "   dump threads [<domain or service> ...]"
    echo "   pool create <size> <directory>"
    echo "   pool add [--fqdn] [--domain=<domain>] [--lfs=<mode>] <pool name> <directory>"
    echo "   pool ls"
    echo "   pool reconstruct <pool name> <target dir>"
    echo "   pool remove <pool name>"
    echo "   restart [<domain or service> ...]"
    echo "   services"
    echo "   start [<domain or service> ...]"
    echo "   status"
    echo "   stop [<domain or service> ...]"
    echo "   version"
    echo
    echo "Size is specified in bytes, or optionally followed by K, M, G or T"
    echo "for powers of 1024. Size is rounded down to the nearest integer "
    echo "number of GiB."
    exit 2
} 1>&2

checkReadlinkf()
{
  if [ ! "$hasReadlinkf" ] ; then
    readlink -f . > /dev/null 2>&1
    hasReadlinkf=$?
  fi
  return $hasReadlinkf
}

# Get the canonical path of $1. Only returns a truely canonical path
# if readlink is available. Otherwise an absolute path which does not
# end in a symlink is returned.
getCanonicalPath() # $1 = path
{
    local link
    link="$1"
    if checkReadlinkf ; then
        RET="$(readlink -f $link)"
    else
        RET="$(cd $(dirname $link); pwd)/$(basename $link)"
        while [ -h "$RET" ]; do
            link="$(ls -ld $RET | sed 's/.*-> //')"
            if [ -z "${link##/*}" ]; then
                RET="${link}"
            else
                link="$(dirname $RET)/${link}"
                RET="$(cd $(dirname $link); pwd)/$(basename $link)"
            fi
        done
    fi
}

# Returns true if $1 is contained as a word in $2.
contains() # $1 = word, $2+ = list
{
    local word
    word=$1
    shift
    for i in "$@"; do
        if [ "$word" = "$i" ]; then
            return 0
        fi
    done
    return 1
}

# Generic option parser. Both single and multi character options are
# supported. Single character options start with a single dash and
# multi character options with a double dash. Single character options
# can be combined, e.g. rather than -a -b -c one can use -abc.
#
# The first argument is a list of valid options. Remaining arguments
# are the options to be parsed. When finding an option not in the list
# of valid options, the usage() is called.
#
# Parsing stops when no arguments are left or a non-option argument
# is found.
#
# Options can have an optional value.
#
# For each option found the variable opt_X, where X is the
# option, is defined. If a value is provided for the option, then
# opt_X is set to that value, otherwise to 1.
#
# The return value is the number of words of $1 that were processed.
#
parseOptions() # $1 = list of valid options
{
    local valid
    local count
    local name
    local value
    local rest
    local option

    valid=$1
    count=0

    shift
    while [ $# -gt 0 ]; do
        option=$1
        case $option in
            --*=*)
                option=${option#--}    # Strip leading double dash
                name=${option%%=*}
                value=${option#*=}
                ;;

            -?=*)
                option=${option#-}     # Strip leading dash
                name=${option%%=*}
                value=${option#*=}
                ;;

            --?*)
                name=${option#--}      # Strip leading double dash
                value=1
                ;;

            -?*)
                option=${option#-}     # Strip leading dash
                while [ -n "$option" ]; do
                    rest=${option#?}       # Strip leading character
                    name=${option%${rest}} # Strip the rest to get name
                    if ! contains $name $valid; then
                        usage
                    fi

                    option=${rest}

                    eval "opt_${name}=1"
                done
                count=$((${count}+1))
                shift
                continue
                ;;

            *)
                break
                ;;
        esac

        if ! contains $name $valid; then
            usage
        fi

        eval "opt_${name}=${value}"

        shift
        count=$((${count}+1))
    done

    return $count
}

# Sets the jmap variable such that it contains the command to invoke
# the jmap utility. Exits if jmap could not be found.
requireJmap()
{
    if [ -n "$jmap" ]; then
        if [ ! -x "$jmap" ]; then
            return 0
        fi
    else
        jmap="$(dirname ${java})/jmap"
        if [ -x "$jmap" ]; then
            return 0
        fi

        if [ -n "$JAVA_HOME" ]; then
            jmap="$JAVA_HOME/bin/jmap"
            if [ -x "$jmap" ]; then
                return 0
            fi
        fi
    fi

    fail 1 "Could not find the jmap command, part of the Java 6 JDK.
            This command is required for producing a heap dump. Please
            ensure that either jmap is in the path or update
            dCacheSetup to point to its location."
}

# Dumps the heap. Terminates the script in case of failure.
dumpHeap() # $1=force, $2=live, $3=file, $4=pid, $5=error
{
    if ! $jmap ${1:+-F} -dump:${2:+live,}format=b,file=$3 $4; then
        fail 1 "$5"
    fi

    if [ ! -f "$3" ]; then
        fail 1 "$5"
    fi
}

# display dCache package version
showVersion()
{
    ${java} -jar ${classesDir}/dcache.jar
}

# Parse global options
parseOptions "d" $*
shift $?

if [ $# -eq 0 ]; then
    usage
fi

# Set home path
if [ -n "$opt_d" ]; then
    DCACHE_HOME="$opt_d"
elif [ -z "$DCACHE_HOME" ]; then
    getCanonicalPath "$0"
    DCACHE_HOME=${RET%/bin/dcache}
fi

if [ ! -d "$DCACHE_HOME" ]; then
    echo "$DCACHE_HOME is not a directory"
    exit 2
fi

# Load libraries
. ${DCACHE_HOME}/share/lib/paths.sh
. ${DCACHE_LIB}/utils.sh
. ${DCACHE_LIB}/config.sh
. ${DCACHE_LIB}/services.sh
. ${DCACHE_LIB}/namespace.sh
. ${DCACHE_LIB}/pool.sh

# Check prerequisites
require awk df egrep grep sed cat hostname wc dirname basename mount mv

# Read configuration files
readconf ${DCACHE_HOME}/etc/node_config NODE_CONFIG_ ||
readconf ${DCACHE_HOME}/etc/door_config NODE_CONFIG_
loadConfigurationFile dCache dCache
loadConfigurationFile pool pool

# We sometimes need to start java; import the path from dCacheSetup
java="${dCache_java}"
classesDir="${dCache_classesDir}"

# Sanitycheck for java
if [ -z "${java}" ] || [ ! -x "${java}" ] || ! ${java} -version 2>&1 | egrep -e 'version "1\.[6]' >/dev/null ; then
    fail 1 "The variable 'java' in ${ourHomeDir}/config/dCacheSetup
            has to be set to a Java VM version 6."
fi

determineHostName

case "$1" in
    start)
        shift
        domains=$(printExpandedServiceAndDomainList $*)

        if isNameSpaceMountNeeded $domains; then
            autoMountNameSpace
        fi

        for domain in $domains; do
            runDomain $domain start
        done

        touch $DCACHE_LOCK 2> /dev/null || :
        ;;

    stop)
        shift
        domains=$(printExpandedServiceAndDomainList $*)

        reverse $domains; domains_backward="$RET"
        for domain in $domains_backward; do
            if getPidOfDomain $domain; then
                runDomain $domain stop
            fi
        done

        rm -f $DCACHE_LOCK
        ;;

    restart)
        shift
        domains=$(printExpandedServiceAndDomainList $*)

        reverse $domains; domains_backward="$RET"
        for domain in $domains_backward; do
            if getPidOfDomain $domain; then
                runDomain $domain stop
            fi
        done

        if isNameSpaceMountNeeded $domains; then
            autoMountNameSpace
        fi

        for domain in $domains; do
            runDomain $domain start
        done
        ;;

    condrestart)
        shift
        domains=$(printExpandedServiceAndDomainList $*)

        reverse $domains; domains_backward="$RET"
        for domain in $domains_backward; do
            if getPidOfDomain $domain; then
		running_domains="$running_domains $domain"
                runDomain $domain stop
            fi
        done

        reverse $running_domains; domains_to_start="$RET"
        for domain in $domains_to_start; do
            runDomain $domain start
        done
        ;;

    status)
        domains=$(printAllDomains)
        maxWidth $domains; width="$RET"
        format="%-${width}s %-16s %s\n"
        printf "$format" "Domain" "Service" "Status"
        for domain in $domains; do
            if ! getPidOfDomain $domain; then
                status="stopped"
            elif getJavaPidOfDomain $domain; then
                status="running"
            else
                status="restarting"
            fi

            if getService $domain; then
                service="$RET"
            else
                service=""
            fi

            printf "$format" "$domain" "$service" "$status"
        done
        ;;

    services)
        domains=$(printAllDomains)
        maxWidth $domains; width="$RET"
        format="%-${width}s %-10s %s\n"
        printf "$format" "Domain" "Service" "Log"
        for domain in $domains; do
            if getService $domain; then
                service="$RET"
            else
                service=""
            fi

            if getLogOfDomain ${domain} && [ -f "$RET" ]; then
                log="$RET"
            else
                log=""
            fi

            printf "$format" "$domain" "$service" "$log"
        done
        ;;

    version)
        showVersion
    ;;

    pool)
        shift

        if [ $# -eq 0 ]; then
            usage
        fi

        command=$1
        shift

        case "$command" in
            ls)
                [ $# -gt 0 ] && usage

                domains=$(printAllPoolDomains)
                pools=$(printAllPools $domains)
                maxWidth $pools; width_1="$RET"
                maxWidth $domains; width_2="$RET"
                format="%-${width_1}s %-${width_2}s %-9s %7s%7s %s\n"
                printf "$format" "Pool" "Domain" "LFS" "Size" "Free" "Path"
                for domain in $domains; do
                    printPoolsInDomain $domain | while read pool path param; do
                        lfs=$(echo $param | sed -n -e 's/.*lfs=\([^ ]*\).*/\1/p')
                        if [ -f "${path}/setup" ]; then
                            getSizeOfPool $path; size="$RET"
                            getFreeSpace $path; free="$RET"
                            printf "$format" "$pool" "$domain" "$lfs" "$size" "$free" "$path"
                        else
                            printf "$format" "$pool" "$domain" "$lfs" "-" "-" "$path (missing)"
                        fi
                    done
                done

                echo
                printp "Disk space is measured in GiB. Free space is
                        reported for the partition containing the pool,
                        not for the pool itself."
                ;;

            create)
                [ $# -ne 2 ] && usage

                size=$1
                path=$2

                createPool ${size} ${path}
                ;;

            add)
                parseOptions "domain fqdn lfs" $*
                shift $?

                [ $# -ne 2 ] && usage
                pool=$1
                path=$2

                addPool ${pool} ${path} ${opt_domain:-"${hostname}Domain"} ${opt_fqdn:-0} ${opt_lfs:-precious}
                ;;

            remove)
                [ $# -ne 1 ] && usage
                pool=$1
                removePool ${pool}
                ;;

            reconstruct)
                [ $# -ne 2 ] && usage
                pool="$1"
                dst="$2"

                # First find the domain containing the pool
                domains=$(printAllPoolDomains)
                if ! getDomainOfPool "$pool" $domains; then
                    fail 2 "Cannot find a pool named $pool."
                fi
                domain="$RET"

                # Make sure the pool is not running right now
                if getPidOfDomain "$domain"; then
                    fail 1 "$domain contains $pool, however the domain is
                            still running. Please stop the domain before
                            attempting to reconstruct the meta data. The
                            domain can be stopped using the command
                            '$0 stop $domain'."
                fi

                # Find the path to the pool
                getPoolPath "$pool" "$domain" || fail 1 "Failed to locate pool"
                path="$RET"

                # Check that we have a meta directory
                if [ ! -d "$path/meta" ]; then
                    fail 2 "$pool appears to be stored in $path, however the
                            pool appears not to have a Berkeley DB holding the
                            meta data, as there is no $path/meta directory."
                fi

                # Make sure the destination does not exist
                if [ -e "$dst" ]; then
                    fail 2 "$dst already exists. The target directory must"
                           "not exist prior to recovering a pool."
                fi

                # Reconstruct the DB
                mkdir -p "$dst" || fail 1 "Failed to create $dst"
                reconstructMeta "${path}/meta" "${dst}" || fail 1 "Operation aborted"

                printp "The pool meta data database of $pool was reconstructed
                        and stored in $dst. You have to manually replace
                        $path/meta with the content of $dst."
                ;;


            *)
                usage
                ;;
        esac

        ;;

    dump)
        shift

        if [ $# -eq 0 ]; then
            usage
        fi

        command=$1
        shift

        case "$command" in
            heap)
                parseOptions "force" $*
                shift $?

                [ $# -ne 2 ] && usage

                domain=$1
                file=$2

                requireJmap

                if [ -f ${file} ]; then
                    fail 1 "${file} already exists. Heap not dumped."
                fi

                if ! getJavaPidOfDomain ${domain}; then
                    fail 1 "Domain ${domain} is not running."
                fi
                pid="$RET"

                if [ -z "$opt_force" ]; then
                    dumpHeap "" "live" "$file" "$pid" \
                         "Failed to dump the heap; please consult
                          the previous error message for possible
                          reasons. The dump might succeed when using 
                          the --force option."
                else
                    dumpHeap "force" "" "$file" "$pid" \
                         "Failed to dump the heap; please consult
                          the previous error message for possible
                          reasons."
                fi

                printp "The heap of domain ${domain} has been written to
                        ${file}. Notice that the file might contain
                        confidential information."
                ;;

            threads)
                domains=$(printExpandedServiceAndDomainList $*)
                for domain in $domains; do
                    if getJavaPidOfDomain ${domain}; then
                        if ! kill -s QUIT ${RET}; then
                            fail 1 "Failed to dump stack traces. Likely
                                    the current user does not have the
                                    proper permissions."
                        fi
                    fi
                done

                printp "Stack traces have been written to the log files."
                ;;

            *)
                usage
                ;;
        esac
        ;;

    *)
        usage
        ;;
esac
