#!/bin/zsh
# すまんnkfとか無くてももっと簡単な事だった。
# 後<span>を削る必要は無いけど扱いやすくなるから残しとく。
UNIQ=$(printf $(ps -p $PPID -o pid,ppid,lstart |md5sum))

case "$QUERY_STRING" in
# formから流れてくるもの。
${UNIQ}=form\&*)
URL="https://www.google.co.jp/search?$( cut -d '&' -f 2- <<<$QUERY_STRING )";;
${UNIQ}=rotate\&*) # 次のページへ、ここから再検索して下さい、時間指定等の対応。
URL="https://www.google.co.jp/$( cut -d '&' -f 2- <<<$QUERY_STRING )";;
*) # default.
URL="https://www.google.co.jp/search?q=$QUERY_STRING&;hl=ja&biw=&bih=&gbv=1&num=100";;
esac

<<EOF
Content-Type: text/plain
w3m-control: GOTO $URL
w3m-control: VIEW
w3m-control: PIPE_BUF sed 's%\(<input[^>]*\)Shift_JIS%\1UTF-8%; s%\(<form \)\([^>]*>\)'\
'%\1action="file:///cgi-bin/google.zsh" \2<input name=$UNIQ type=hidden value="form">%;'\
's%\(<span[^>]*>\|</span>\)%%g; s%<div[^>]*>%%g; s%</div>%<div>&%g;'\
's,\(<a [^>]*href="\)/\(search?\|url?q=/search%3F\)\([^"]*"\)'\
',\1file:///cgi-bin/google.zsh?${UNIQ}=rotate\&\2\3,g;'\
's%\(<a [^>]*href="\)/url?%\1https://www.google.co.jp/url?%g'
w3m-control: VIEW
$( printf '%s\n' 'w3m-control: DELETE_PREVBUF'{,,,} )

EOF