#!/bin/bash

## Init is run on host
## For now it is run every time the script is launched, but
## it should be launched only once after build.

## Accessible variables are:
## - SERVICE_NAME        Name of current service
## - DOCKER_BASE_IMAGE   Base image from which this service might be built if any
## - SERVICE_DATASTORE           Location on host of the DATASTORE of this service
## - SERVICE_CONFIGSTORE         Location on host of the CONFIGSTORE of this service


. lib/common

set -e

admin_user=$(options-get admin.user 2>&1) || {
    admin_user="admin"
}

first_run=0
read-0 current_user current_password < <(get_admin_user_password) || {
    info "Probably no admin user and password set before."
    first_run=1
}

admin_password=$(options-get admin.password 2>&1) ||
admin_password=$(options-get admin-password 2>&1) || {
    if [ "$current_password" ]; then
        admin_password="$current_password"
    else
        info "Generating ${DARKYELLOW}$MASTER_BASE_SERVICE_NAME${NORMAL}'s"\
             "admin password"
        admin_password=$(gen_password)
    fi
}

## We can't do anything with 'occ' before installation through
## postgres relation because the way 'entrypoint.sh' provided by
## nextcloud handles installation : it will not completely install
## nextcloud (it doesn't launch 'maintenance:install'), making
## nextcloud half installed and commands like 'user:*' unavailable.

## Nicely enough, we don't need to do anything password wise if
## postgres was never launched before.
if [ "$first_run" == 0 ]; then
    if [ "$current_password" != "$admin_password" ] ||
           [ "$current_user" != "$admin_user" ]; then
        set_admin_user_password "$admin_user" "$admin_password" || {
            err "Failed to set admin user and password."
            exit 2
        }
    fi
else
    mkdir -p "$(dirname "$PASSWORD_FILE")"
    p0 "$admin_user" "$admin_password" > "$PASSWORD_FILE"
fi

## XXXvlab: the directory here for datadir violates DRY as it is also
## in ``metadata.yml``
init-config-add "\
$MASTER_BASE_SERVICE_NAME:
  environment:
    NEXTCLOUD_ADMIN_USER: $admin_user
    NEXTCLOUD_ADMIN_PASSWORD: $admin_password
    NEXTCLOUD_DATA_DIR: /var/lib/nextcloud/data
    NEXTCLOUD_TRUSTED_DOMAINS: '\*'
"

## ensuring data directories are accessible by nextcloud

uid=$(docker_get_uid "$MASTER_BASE_SERVICE_NAME" "www-data")


dirs=("$SERVICE_DATASTORE/var/lib/nextcloud/data" "$SERVICE_DATASTORE/var/www/html")
mkdir -p "${dirs[@]}"
chown -R "$uid" "${dirs[@]}"