#!/bin/sh

# Copyright (c) 2000
#      Tanaka Akira. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
# 3. The name of the author may not be used to endorse or promote products
#    derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

###

: ${CVSCONNECT_CONNECTION:=default}

server_pid_file=$CVSCONNECT_BASE/$CVSCONNECT_CONNECTION.server.pid
sleep1_pid_file=$CVSCONNECT_BASE/$CVSCONNECT_CONNECTION.sleep1.pid
sleep2_pid_file=$CVSCONNECT_BASE/$CVSCONNECT_CONNECTION.sleep2.pid
c2s=$CVSCONNECT_BASE/$CVSCONNECT_CONNECTION.c2s
s2c=$CVSCONNECT_BASE/$CVSCONNECT_CONNECTION.s2c

if [ ! -f $server_pid_file ]; then
  mkfifo $c2s $s2c
  if [ ! -p $c2s -o ! -p $s2c ]; then
    echo "cvsconnect-client: could not create pipes." >&2
    exit 1
  fi
  sh -c "
    $CVSCONNECT_BASE/_connect < $c2s > $s2c &
    server_pid=\$!
    echo \$server_pid > $server_pid_file

    sleep 360000 > $c2s &
    sleep1_pid=\$!
    echo \$sleep1_pid > $sleep1_pid_file

    sleep 360000 < $s2c &
    sleep2_pid=\$!
    echo \$sleep2_pid > $sleep2_pid_file

    exec 2>/dev/null # to suppress a message 'PID: Terminated' by ash.
    wait \$server_pid
    rm $server_pid_file
    rm $sleep1_pid_file && kill \$sleep1_pid
    rm $sleep2_pid_file && kill \$sleep2_pid
  " </dev/null >/dev/null 2>/dev/tty \
                       3>&-  4>&-  5>&-  6>&-  7>&-  8>&-  9>&- \
    10>&- 11>&- 12>&- 13>&- 14>&- 15>&- 16>&- 17>&- 18>&- 19>&- &
fi

read -r line # skip "Root ..."

cat < $s2c &
s2c_pid=$!

cat > $c2s

exec 2>/dev/null # to suppress a message 'PID: Terminated' by ash.
kill $s2c_pid

exit 0
