#!/bin/bash

piece=$1
ooo_build_tag=$2
src_root=$3
shift; shift; shift;

source $OO_TOOLSDIR/piece/sys-setup

# do we need to do anything?
test "$src_root" = "$DESTDIR" && test "$OOO_BUILD_NOARCH" != 'YES' && exit 0

target_instdir="$OO_INSTDIR"
test "$OOO_BUILD_NOARCH" = 'YES' && target_instdir="$OO_INSTDIR_SHARE"
    
echo "Installing l10n stuff to the final location..."

for filelist in $@ ; do
    test -f $filelist || continue;
    echo -n "   processing $filelist... "
    # we wants to create even empty directories
    for source_dir in `grep "^%dir" $filelist | sed "s|^%dir[[:blank:]]*||" | sort -ru` ; do
	target_dir=`echo $source_dir | sed "s|$OO_INSTDIR|$target_instdir|"`
	mkdir -p "$DESTDIR$target_dir"
    done
    # install files
    for source_file in `grep -v "^%dir" $filelist | sort -ru` ; do
	target_file=`echo $source_file | sed "s|$OO_INSTDIR|$target_instdir|"`
	if test "$src_root" = "$DESTDIR" ; then
	    # moving inside DESTDIR; must be moving from /usr/lib to /usr/share
	    mv "$src_root$source_file" "$DESTDIR$target_file"
	else
	    # most likely copying from the system solver (prebuilt l10n stuff)
	    cp "$src_root$source_file" "$DESTDIR$target_file"
	fi
    done
    # remove empty directories when moved inside DESTDIR
    if test "$src_root" = "$DESTDIR" ; then
	for source_dir in `grep "^%dir" $filelist | sed "s|^%dir[[:blank:]]*||" | sort -ru` ; do
	    rmdir --ignore-fail-on-non-empty $src_root/$source_dir
	done
    fi
    # update the file list when moved to /usr/share
    if test "$OOO_BUILD_NOARCH" = 'YES' ; then
	sed "s|$OO_INSTDIR|$target_instdir|" $filelist >>$filelist.new
	mv $filelist.new $filelist
	# we need the file list installed to create compat symlinks in %post
	# FIXME: We should fix OOo to find the files in /usr/share directly
        cp $filelist $DESTDIR$target_instdir/
	echo "$target_instdir/$filelist" >>$filelist
    fi
    
    echo "done"
done
