#!/bin/bash
export LANG=en_EN.UTF-8
export NOLOCALE=yes
export PATH=/sbin:/bin:/usr/sbin:/usr/bin


[[ -z $DEBUG   ]] && DEBUG=0
BASE_DIR=/opt/webdir
LOGS_DIR=$BASE_DIR/logs
TEMP_DIR=$BASE_DIR/temp

CURL_OPTS='--connect-timeout 2 --max-time 5 --retry 3'
CURL_OPTS=$CURL_OPTS' --user-agent "Bitrix Installation agent"'
URL='https://download.documentfoundation.org/libreoffice/stable/'
TMP_FILE=$(mktemp /tmp/libreoffice_version_XXXXXXX)

# print error message
print_error() {
    msg=$1
    echo "{\"changed\":false,\"failed\":true,\"msg\":\"$msg\"}"

    if [[ -n $TMP_FILE && -f $TMP_FILE ]]; then
        rm -f $TMP_FILE
    fi

    exit 1
}

# print timezone info
print_ok() {
    version=$1

    echo "{\"changed\":true,\"ansible_facts\": {\"libreoffice_version\":\"$version\"}}"
    if [[ -n $TMP_FILE && -f $TMP_FILE ]]; then
        rm -f $TMP_FILE
    fi
 
    exit 0
}

curl $CURL_OPTS -s "$URL" > $TMP_FILE 2>&1
if [[ $? -gt 0 ]]; then
    print_error "Cannot get version from $URL; $(cat $TMP_FILE)"
fi

VERSION=$(cat $TMP_FILE | \
    egrep -o '"[0-9\.]+/"' | tail -n 1 | \
    sed -e 's/"//g;s/\///')
if [[ -z $VERSION ]]; then
    print_error "Cannot find latest stable version from $URL"
fi

print_ok "$VERSION"

