+# example usage:
+# github-release-dl restic/restic restic_ _linux_amd64.bz2
+# gets a url like:
+# https://github.com/restic/restic/releases/download/v0.16.3/restic_0.16.3_linux_amd64.bz2
+github-release-dl() {
+ local github_path file_prefix file_suffix latest_prefix version redir_path
+ github_path=$1
+ file_prefix=$2
+ file_suffix=$3
+ if (( $# != 3 )); then
+ echo "$0: error, expected 3 arguments" >&2
+ return 1
+ fi
+ redir_path="https://github.com/$github_path/releases/latest/download/"
+ latest_prefix=$(curl -s -I "$redir_path" | awk 'tolower($1) == "location:" {print $2}')
+ # it has a trailing /r at the end. just kill any whitespace.
+ latest_prefix="${latest_prefix//[$'\t\r\n ']}"
+ if [[ ! $latest_prefix ]]; then
+ echo "failed to find latest path. Tried to find case insensitive 'location:' in the curl output:"
+ m curl -s -I "$redir_path"
+ return 1
+ fi
+ version="${latest_prefix##*/}"
+ version="${version#v}"
+ m wget -- "$latest_prefix/$file_prefix$version$file_suffix"
+}
+
+# examples.
+# go-github-install restic/restic restic_ _linux_amd64.bz2
+# go-github-install restic/rest-server rest-server_ _linux_amd64.tar.gz
+
+# common pattern among go binaries on github
+go-github-install() {
+ local tmpd targetf tmp files src
+ tmpd=$(mktemp -d)
+ cd $tmpd
+ file_prefix=$2
+ file_suffix=$3
+ tmp="${file_prefix##*[[:alnum:]]}"
+ targetf="${file_prefix%"$tmp"}"
+ echo targetf: $targetf
+ github-release-dl "$@"
+ files=(./*)
+ case $file_suffix in
+ *.bz2)
+ bunzip2 -- ./*
+ ;;
+ *.tar.gz|*.tgz)
+ tar -vxzf ./*
+ ;;
+ esac
+ rm -f -- "${files[@]}"
+ files=(./*)
+ # Here we detect and handle 2 cases: either we extracted a single
+ # binary which we have to rename or a folder with a binary named
+ # $targetf in it which is all we care about.
+ if (( ${#files[@]} == 1 )) && [[ -f ${files[0]} ]]; then
+ chmod +x ./*
+ mv -- ./* /usr/local/bin/$targetf
+ else
+ files=(./*/$targetf)
+ if [[ -f $targetf ]]; then
+ src=$targetf
+ elif [[ -f ${files[0]} ]]; then
+ src="${files[0]}"
+ fi
+ chmod +x "$src"
+ mv -- "$src" /usr/local/bin
+ fi
+ cd - >/dev/null
+ rm -rf $tmpd
+}