#!/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

#        if [ -n "${NEXTCLOUD_TRUSTED_DOMAINS+x}" ]; then
#            echo "setting trusted domains…"
#            NC_TRUSTED_DOMAIN_IDX=1
#            for DOMAIN in $NEXTCLOUD_TRUSTED_DOMAINS ; do
#                DOMAIN=$(echo "$DOMAIN" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
#                sh -c "php /usr/src/nextcloud/occ config:system:set trusted_domains $NC_TRUSTED_DOMAIN_IDX --value=$DOMAIN"
#                NC_TRUSTED_DOMAIN_IDX=$(($NC_TRUSTED_DOMAIN_IDX+1))
#            done
#        fi

#        for app in $(cat /usr/src/nextcloud/config/apps_enable); do 
#            app=$(echo $app| cut -d '=' -f1)
#            echo "enabling app $app"
#            sh -c "php /usr/src/nextcloud/occ app:enable $app"
#        done

#        for app in $(cat /usr/src/nextcloud/config/apps_disable); do
#            echo "disabling app $app"
#            sh -c "php /usr/src/nextcloud/occ app:disable $app"
#        done
   fi

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