PO=$(mktemp -d)

log "Exporting PO files from GlotPress (wp/$GP_VER/$GP_LOCALE/$GP_TS_SLUG)..."
$GP_EXPORT "wp/$GP_VER" $GP_LOCALE --set=$GP_TS_SLUG --status=current  > $PO/$WP_LOCALE.po
PO_1=$?
$GP_EXPORT "wp/$GP_VER/admin" $GP_LOCALE --set=$GP_TS_SLUG --status=current > $PO/admin-$WP_LOCALE.po
PO_2=$?
$GP_EXPORT "wp/$GP_VER/admin/network" $GP_LOCALE --set=$GP_TS_SLUG --status=current > $PO/admin-network-$WP_LOCALE.po
PO_3=$?
if [ "${WP_LOCALE:0:3}" != "en_" ]; then
	$GP_EXPORT "wp/$GP_VER/cc" $GP_LOCALE --set=$GP_TS_SLUG --status=current > $PO/continents-cities-$WP_LOCALE.po
	PO_4=$?
else
	PO_4=0
fi

if [ $PO_1 -ne 0 ] || [ $PO_2 -ne 0 ] || [ $PO_3 -ne 0 ] || [ $PO_4 -ne 0 ]; then
	log "PO export failed."
	log "Exit codes: dev $PO_1, admin $PO_2, network $PO_3, cc $PO_4"
	ls -la $PO
	rm -r $PO
	exit 1
fi

log "Generating MO files..."
msgfmt $PO/$WP_LOCALE.po                   -o $PO/$WP_LOCALE.mo
PO_1=$?
msgfmt $PO/admin-$WP_LOCALE.po             -o $PO/admin-$WP_LOCALE.mo
PO_2=$?
msgfmt $PO/admin-network-$WP_LOCALE.po     -o $PO/admin-network-$WP_LOCALE.mo
PO_3=$?
if [ "${WP_LOCALE:0:3}" != "en_" ]; then
	msgfmt $PO/continents-cities-$WP_LOCALE.po -o $PO/continents-cities-$WP_LOCALE.mo
	PO_4=$?
else
	PO_4=0
fi

if [ $PO_1 -ne 0 ] || [ $PO_2 -ne 0 ] || [ $PO_3 -ne 0 ] || [ $PO_4 -ne 0 ]; then
	log "MO generation failed."
	log "Exit codes: dev $PO_1, admin $PO_2, network $PO_3, cc $PO_4"
	ls -la $PO
	rm -r $PO
	exit 1
fi

log "Creating language pack..."
zip -9 -j $PO/$WP_LOCALE.zip $PO/*.po $PO/*.mo > /dev/null # -j junks paths
if [ "$?" -ne 0 ]; then
	rm -r $PO
	log "Language pack ZIP generation failed."
	exit 1
fi
