Update gopher.sh mini test service
[gofetch.git] / gopher.sh
1 #!/bin/bash
2
3 # Note: bash is required, sh will fail to output anything to the client
4 # Probably related to interactions beteween & and output redirections
5
6 # $0 [prog] ([port])
7 # You can use the evironment variable $QUERY_STRING for the query
8
9 [ "$ADDR" = "" ] && ADDR=127.0.0.1
10 [ "$LOG" = "" ] && LOG=/tmp/gopher.service.err
11 [ "$PIDF" = "" ] && PIDF="`mktemp`"
12 [ "$TIMEOUT" = "" ] && TIMEOUT=10
13 [ "$MAXCON" = "" ] && MAXCON=1024
14
15 prog="$1"
16 port="$2"
17 [ "$port" = "" ] && port=70
18
19 if [ "$prog" = "" ]; then
20 rm "$PIDF"
21 echo "Syntax: $0 [prog] ([port])" >&2
22 echo ' You can use the evironment variable $QUERY_STRING for the query' >&2
23 echo ' The default port is 70' >&2
24 echo ' A filename will be displayed, you can delete it to stop the service' >&2
25 echo ' (with a grace time of $TIMEOUT seconds)' >&2
26 exit 1
27 fi
28
29 tmpd=`mktemp -t -d .gopher-service.XXXXXX`
30 if [ ! -d "$tmpd" ]; then
31 rm "$PIDF"
32 echo "Cannot create temporary directory, aborting..." >&2
33 exit 2
34 fi
35
36 touch "$PIDF"
37 echo "$PIDF"
38
39 i=0
40 while [ -e "$PIDF" ]; do
41 i=`expr $i + 1`
42 [ $i -gt "$MAXCON" ] && i=1
43 fifo="$tmpd/fifo.$i"
44 rm -f "$fifo" 2>/dev/null
45 mkfifo "$fifo"
46 < "$fifo" nc -l -q0 -w"$TIMEOUT" "$ADDR" -p "$port" | (
47 read -r query
48 query="`echo "$query" | cut -f2 -d' ' | sed 's:[\r\n]::g'`"
49 QUERY_STRING="$query" "$prog" 2>> "$LOG" &
50 ) > "$fifo"
51 done
52 rm -rf "$tmpd" 2>/dev/null