#! /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

# Sprawdź czy skrypt mediawiki2ency.sh jest w ścieżce wyszukiwania lub
# w bieżącym katalogu.
if ! mediawiki2ency=$(PATH=$PATH:. command -v "mediawiki2ency.sh"); then
	printf '%s: %s %s\n' "$0" 'Nie znaleziono skryptu mediawiki2ency.sh w' \
		'bieżącym katalogu bądź ścieżce wyszukiwania.' >&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=http://micropedia.wikia.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=Encyklopedia::$urlname.txt

	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

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