#!/bin/sh
#
# tun_stone plugin
# Author: Shun-ichi TAHARA <jado@flowernet.gr.jp>
# Time-stamp: <05/03/25 22:43:32 jado@sheira>
#
# Copyright (c) 2004 Shun-ichi TAHARA
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#

# *** Please change below as suitable ***
STONECONF=/usr/local/etc/stonerc
STONEPID=/var/run/stone.pid

# Additional settings going into /etc/network.conf:
#
# STONES : List of stone specs [none|stone -- ...]

TUNSTNDEV=$PLUGINSTATE/tun_stone.devices

tunstn_config ()
{
    cat $TUNSTNDEV | /usr/bin/awk '
	BEGIN{
	    spec = "";
	}
	/^none$/{
	    spec = "none";
	}
	/^[^#]/{
	    if (spec != "none") {
		spec = spec " " $0 " --";
	    }
	}
	END{
	    if (spec != "" && spec != "none") {
		printf("%s\n", spec);
	    }
	}
    '
}

tunstn_update ()
{
    local SPEC=

    if [ ! -x @STONE@ ]; then
	echo "Please install stone to work with STONES."
	return
    fi

    SPEC=`tunstn_config`

    if [ -s "$STONEPID" ]; then
	kill `cat $STONEPID` 2> /dev/null
	rm -f $STONEPID
    fi

    if [ -n "$SPEC" ]; then
	if [ -s "$STONECONF" ]; then
	    eval "@STONE@ -C $STONECONF -i $STONEPID -Dlr $SPEC"
	else
	    eval "@STONE@ -i $STONEPID -Dlr $SPEC"
	fi
    fi
}

# Variables definition

tun_stone_VARS="STONES"

# Script on starting

tun_stone_start ()
{
    touch $TUNSTNDEV
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $TUNSTNDEV > $TUNSTNDEV.N
    if [ -n "$STONES" ]; then
	echo "# $1 begin" >> $TUNSTNDEV.N
	echo "$STONES" >> $TUNSTNDEV.N
	echo "# $1 end" >> $TUNSTNDEV.N
    fi

    mv $TUNSTNDEV.N $TUNSTNDEV
    tunstn_update
}

# Script on stopping

tun_stone_stop ()
{
    /usr/bin/sed -e "/# $1 begin/,/# $1 end/d" $TUNSTNDEV > $TUNSTNDEV.N

    mv $TUNSTNDEV.N $TUNSTNDEV
    tunstn_update
}
