#!/bin/sh
# Copyright 2020 Charles E. Lehner
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

if [ $# -eq 0 ]; then
	echo "Usage: gemini-dl <url>..." >&2
	exit 1
fi

for url; do
	url1=${url#gemini://}
	hostname=${url1%%/*}
	host=${hostname%%:*}
	port=${hostname##*:}
	if [ "$host" = "$port" ]; then port=1965; fi
	page=${url##*/}
	page=${page:-$host}
	file=$page
	i=0
	while test -e "$file"
	do file="$page-$((i = i + 1))"
	done
	printf '%s\r\n' "$url" | openssl s_client -verify_quiet -quiet "$host:$port" | tail +2 | pv -N "$file" > "$file"
done