#!/bin/sh
set -eu

echo "New nextcloud instance"
if [ -n "${NEXTCLOUD_ADMIN_USER+x}" ] && [ -n "${NEXTCLOUD_ADMIN_PASSWORD+x}" ]; then
# shellcheck disable=SC2016
    install_options='-n --admin-user "$NEXTCLOUD_ADMIN_USER" --admin-pass "$NEXTCLOUD_ADMIN_PASSWORD"'
    if [ -n "${NEXTCLOUD_TABLE_PREFIX+x}" ]; then
        # shellcheck disable=SC2016
        install_options=$install_options' --database-table-prefix "$NEXTCLOUD_TABLE_PREFIX"'
    else
        install_options=$install_options' --database-table-prefix ""'
    fi
    if [ -n "${NEXTCLOUD_DATA_DIR+x}" ]; then
    # shellcheck disable=SC2016
        install_options=$install_options' --data-dir "$NEXTCLOUD_DATA_DIR"'
    fi

    install=false
    if [ ${DB_TYPE} = "sqlite" ]; then
        echo "Installing with SQLite database"
        # shellcheck disable=SC2016
        install_options=$install_options' --database-name "$DB_NAME"'
        install=true
    elif [ ${DB_TYPE} = "pgsql" ] || [ ${DB_TYPE} = "mysql" ]; then
        echo "Installing with ${DB_TYPE} database"
        # shellcheck disable=SC2016
        install_options=$install_options' --database $DB_TYPE --database-name "$DB_NAME" --database-user "$DB_USER" --database-pass "$DB_PASSWORD" --database-host "$DB_HOST"'
        install=true
    fi

    if [ "$install" = true ]; then
        echo "starting nexcloud installation"
        max_retries=10
        try=0

        until sh -c "php /usr/src/nextcloud/occ maintenance:install $install_options" || [ "$try" -gt "$max_retries" ]
            do
                echo "retrying install..."
                try=$((try+1))
                sleep 3s
            done

        if [ "$try" -gt "$max_retries" ]; then
            echo "installing of nextcloud failed!"
            exit 1
        fi
   fi

else
    echo "running web-based installer on first connect!"
fi
