#!/bin/bash

# OwnCloud install hooks — latest-version scrape + compose substitution.

owncloud_install_post_compose()
{
    local app_name="$1"

    ((menu_number++))
    echo ""
    echo "---- $menu_number. Obtain latest version number of $app_name"
    echo ""

    local owncloud_version="$CFG_OWNCLOUD_VERSION"
    local webpage_file="/tmp/webpage.html"

    curl -s "https://doc.owncloud.com/docs/next/server_release_notes.html" > "$webpage_file"
    if [ $? -eq 0 ]; then
        local latest_version
        latest_version=$(grep -o 'Changes in [0-9.-]*' "$webpage_file" | awk -F " " '{print $3}' | sort -V | tail -n 1)
        if [ -n "$latest_version" ]; then
            isSuccessful "Latest Retrieved Version: $latest_version"
            isSuccessful "Using for installation"
            owncloud_version="$latest_version"
        else
            isNotice "Failed to extract the latest version from the OwnCloud website."
            isNotice "Defaulting to config value : $CFG_OWNCLOUD_VERSION."
        fi
        rm -f "$webpage_file"
    else
        isNotice "Failed to retrieve the web page."
    fi

    local file_path="$containers_dir$app_name/docker-compose.yml"
    local file_name="docker-compose.yml"
    local result
    result=$(runFileOp sed -i \
        -e "s|OWNCLOUD_SETUP_VERSION|$owncloud_version|g" \
        -e "s|OWNCLOUD_SETUP_ADMIN_USERNAME|$CFG_OWNCLOUD_ADMIN_USERNAME|g" \
        -e "s|OWNCLOUD_SETUP_ADMIN_PASSWORD|$CFG_OWNCLOUD_ADMIN_PASSWORD|g" \
        -e "s|OWNCLOUD_SETUP_HTTP_PORT|$usedport1|g" \
        "$file_path")
    checkSuccess "Updating $file_name for $app_name"
}
