#!/bin/bash

if [[ "$#" -eq 0 ]]; then
   echo "Usage: $0 [-l] google search terms..." >&2
   echo "Launches links from the command line on the #1 ghit." >&2
   exit 1
fi

LIST=false
if [[ "$1" = -l ]]; then LIST=true; shift; fi

wget -U 'Links (2.12; Linux 4.4.0-21-generic x86_64; GNU C 5.2.1; text)' https://www.google.com/search?q="$(echo "$@" | sed 's/ /+/g')" -O - |
perl -lne 'print $1 while m,(?:fuLhoc|ZWRArf).*?" href="/url\?q=(.*?)[&"],g' |  # probably should fix this to be less fragile...
sed 's/&amp;/\&/g' |
perl -pne 's/%(..)/chr(hex($1))/ge' |
if $LIST; then cat; else links "$(head -1)" </dev/tty; fi
