#!/bin/bash
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA  02111-1307 USA
#
#
# This script bulk export patron images from a Koha instance and generate DATALINK.TXT to import into another instance
# 
# 
# © 2014 "Pablo A. Bianchi" <pablo.bianchi@gmail.com>
# Faculty of Engineering - University of Buenos Aires


echo "This script bulk export patron images from a Koha instance and generate DATALINK.TXT to import into another instance."

# [PARAMS]
koha_host="http://<staff_host>:8080"
dbname="koha_INSTANCE"
username="root"	# Will prompt for password
query="SELECT borrowers.borrowernumber AS borrowernumber, cardnumber, REPLACE(mimetype,'image/','') FROM borrowers JOIN patronimage ON (borrowers.borrowernumber = patronimage.borrowernumber) WHERE borrowers.borrowernumber IS NOT NULL AND cardnumber IS NOT NULL"
datalink_filename="DATALINK.TXT"
# [/PARAMS]

rm --force "$datalink_filename"

mysql "$dbname" -u "$username" -p -s -e "$query" | while read borrowernumber cardnumber extension; do
	if wget -q -N "$koha_host/cgi-bin/koha/members/patronimage.pl?borrowernumber=$borrowernumber" -O "$cardnumber.$extension"; then
		echo "$cardnumber, $cardnumber.$extension" | tee -a "$datalink_filename"
	else
		rm "$cardnumber.$extension"
	fi
done

exit 0;
