gopher.sh: disabling the escape sequences with ENV
[gofetch.git] / gopher.sh
1 #!/bin/sh
2
3 # ENV variables:
4 # LINK_COLOR: escape sequences colour (def: 2)
5 # - : means no escape sequence
6 # 1 : means colour 1
7 # 2 : means colour 2
8 # [...]
9
10 SERVER="$1"
11 SELECTOR="$2"
12 PORT="$3"
13 MODE="$4"
14
15 # Defaults:
16 [ "$PORT" = "" ] && PORT=70
17 if [ "$MODE" = "" ]; then
18 # "" or dir-like selector? -> 1 ; if not -> 0
19 echo "$SELECTOR" | grep "/$" >/dev/null && MODE=1 || MODE=0
20 [ "$SELECTOR" = "" ] && MODE=1
21 fi
22
23 if [ "$SERVER" = "" ]; then
24 echo "Syntax error: $0 [SERVER] ([SELECTOR]) ([PORT]) ([MODE])" >&2
25 exit 2
26 fi
27
28 # can be "-" for no escape sequences
29 [ "$LINK_COLOR" = "" ] && LINK_COLOR=2
30
31 # Start and end link tags
32 SL=
33 EL=
34 if [ "$LINK_COLOR" != "-" ]; then
35 SL="`tput setf $LINK_COLOR``tput setaf $LINK_COLOR`"
36 EL="`tput init`";
37 fi
38
39 # $0 [FILE]
40 # Display a gopher menu for the given resource
41 cat_menu() {
42 i=0
43 cat "$1" | grep '^[i0-9]' | while read ln; do
44 ln="`echo "$ln" | cut -f1`"
45 if echo "$ln" | grep "^i" >/dev/null 2>&1; then
46 echo "$ln" | sed "s:^.: :g"
47 elif echo "$ln" | grep "^[0-9]" >/dev/null 2>&1; then
48 i=`expr $i + 1`
49 i=`printf %2.f $i`
50 field="`echo "$ln" | cut -c1`"
51 case "$field" in
52 0) typ='TXT';;
53 1) typ='DIR';;
54 7) typ='(?)';;
55 8) typ='TEL';;
56 *) typ='!!!';;
57 esac
58 echo "$ln" | sed "s:^.\\(.*\\):$typ $i $SL\\1$EL:g"
59 #else
60 # Bad line
61 fi
62 done
63 }
64
65 # $0 [FILE] [INDEX] [FIELD]
66 # Get a field from the given-by-index link in FILE
67 #
68 # Fields:
69 # 1 = type/name
70 # 2 = selector
71 # 3 = server
72 # 4 = port
73 getsel() {
74 cat "$1" | grep '^[0-9]' | tail -n+"$2" | head -n 1 | cut -f"$3"
75 }
76
77 tmp="`mktemp -t gofetch.current_page.XXXXXX`"
78 finish() {
79 rm -rf "$tmp"
80 }
81 trap finish EXIT
82
83 if [ $MODE = 1 ]; then
84 echo "$SELECTOR" | nc "$SERVER" "$PORT" | sed 's:\r::g' > "$tmp"
85 else
86 echo "$SELECTOR" | nc "$SERVER" "$PORT" > "$tmp"
87 fi
88
89 case "$MODE" in
90 0)
91 cat "$tmp" | less
92 ;;
93 1)
94 CHOICE=start
95 while [ "$CHOICE" != "" ]; do
96 cat_menu "$tmp" | less
97 read -p "[$SELECTOR]: " CHOICE
98 index="`expr 1 \* "$CHOICE" 2>/dev/null`"
99 if [ "$index" != "" ]; then
100 goto_server="`getsel "$tmp" $index 3`"
101 goto_sel="`getsel "$tmp" $index 2`"
102 goto_port="`getsel "$tmp" $index 4`"
103 goto_mode="`getsel "$tmp" $index 1 | cut -c1`"
104 sh "$0" "$goto_server" "$goto_sel" "$goto_port" "$goto_mode"
105 fi
106 done
107 ;;
108 7)
109 read -p "Query: " SEARCH
110 selQuery="$SELECTOR $SEARCH"
111
112 exec sh "$0" "$SERVER" "$selQuery" "$PORT" 1
113 ;;
114 8)
115 telnet -l "$SELECTOR" "$SERVER" "$PORT"
116 read DUMMY
117 ;;
118 9)
119 echo "<BINARY FILE>" | less
120 ;;
121 *)
122 echo "unknwon selector mode: <$MODE>" | less
123 exit 3
124 ;;
125 esac