#!/usr/local/bin/bash
# -*- sh -*-

: << =cut

=head1 NAME

http_loadtime - Plugin to graph HTTP response time of a specific page

=head1 CONFIGURATION

The following environment variables are used by this plugin

 target - URL to fetch (default: "http://localhost/")

=head1 AUTHOR

Unknown authors
(2013) Axel Huebl

=head1 LICENSE

GPLv2

=head1 MAGIC MARKERS

 #%# family=auto
 #%# capabilities=autoconf

=cut

target=${target:-"http://localhost/"}
wget_opt="--user-agent munin/http_loadtime --no-cache -q --delete-after"
time_bin=`which time`

if [ "$1" = "autoconf" ]; then
    result="yes"
    command -v $time_bin 2>&1 >/dev/null || result=1
    command -v tr        2>&1 >/dev/null || result=1
    command -v wget      2>&1 >/dev/null || result=1
    if [ "$result" != "yes" ]; then
	echo "no (programs time, wget and tr required)"
	    exit 0
    fi
    if ! $wget_bin -q -O /dev/null $target; then

    # check if url responds
    #
    wget --spider $target $wget_opt
    if [ "$?" != "0" ]; then
        echo "no (Cannot run wget against \"$target\")"
        exit 0
    fi
    echo yes
    exit 0
fi

if [ "$1" = "config" ]; then
    echo "graph_title HTTP loadtime of a page"
    echo "graph_args --base 1000 -l 0"
    echo "graph_vlabel Load time in seconds"
    echo "graph_category network"
    echo "graph_info This graph shows load time in seconds of $target"
    echo "loadtime.label loadtime"
    echo "loadtime.info Load time"
    exit 0
fi

TEMPO_DIR=$(mktemp -dt munin_http_loadtime.XXXXXX) || exit 1

trap "rm -rf $TEMPO_DIR" EXIT

cd $TEMPO_DIR || exit 1
loadtime=`$time_bin --quiet -f "%e" wget $wget_opt $target 2>&1`
cd -

echo "loadtime.value $loadtime"
