#!/usr/bin/env bash

# last mod 23/10/2012 16.51
# convert libreoffice ods in ms xlsx
LOGFILE=/tmp/error_libreoffice_conversion.log

if [[ $# = 0 ]]; then
    echo "Usage: $0 file1.ods ..."
    exit 1
fi

if [[ -n $(pgrep soffice) ]]; then
    echo "Close all libreoffice instance before"
    exit 1
fi

for i in $@;
do
    #check
    if [[ ! -f "$i" || -z $(echo "$i" | grep -E '\.ods$') ]]; then
        echo "Only .ods files are accepted ($i)"
        continue
    fi

    # convert
    echo -n "convert ${i}: "
    libreoffice -nologo -convert-to "xlsx" "$i"  2>&1 >> $LOGFILE
    
    # result
    if [[ $? = 0 ]]; then
        msg="File converted successfully"
    else
        msg="An error occurred (view $LOGFILE )"
    fi
    echo "$msg"
done

exit 0