#! /bin/sh
# Importuje artykuły z Micropedii i SclaviniaWiki z listy podanej na
# standardowym wejściu.
# Copyright © 2017 Paulina Laura Emilia <vilene@posteo.net>
#
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See the
# COPYING file for more details.
set -C

# Znajdź katalog w którym znajduje się ten skrypt.
scriptdir=$(cd -P "$(dirname "$0")" && pwd)

# Sprawdź czy skrypt mediawiki2ency.sh jest w ścieżce wyszukiwania lub
# w katalogu w którym znajduje się ten skrypt.
if ! mw2e=$(PATH=$PATH:$scriptdir command -v "mediawiki2ency.sh"); then
	printf "%s: Nie znaleziono skryptu \`mediawiki2ency.sh' w katalogu \`%s' bądź w ścieżce wyszukiwania.\n" \
		"$0" "$scriptdir" >&2
	exit 1
fi

# Wybierz prefiks URL-a stron w zależności od źródła.
case $1 in
--sclavinia)
	prefix=http://vonthorn.sarmacja.org/wiki/index.php/
	;;
*)
	prefix=https://micropedia.fandom.com/wiki/
esac

# Czytaj listę ze standardowego wejścia.
while IFS= read -r name; do
	urlname=$(printf '%s\n' "$name" | sed -e 's/ /_/g')
	filename=$urlname.markdown

	if [ -e "$filename" ]; then
		printf '%s: %s: %s\n' "$0" "$filename" 'Plik już istnieje.' >&2
		continue
	fi

	if ! curl -fso "$filename.tmp" "$prefix$urlname?action=raw"; then
		printf '%s: %s: %s\n' "$0" "$name" \
			'Nie udało się pobrać artykułu.' >&2
		continue
	fi

	"$mw2e" "$@" "$filename.tmp" "$name" > "$filename"
	rm -f "$filename.tmp"
done
