#!/bin/bash
set -euo pipefail

error() {
    >&2 echo "[ERROR] $1"
}

CONFIG="/fietsboek/fietsboek.ini"
if [[ ! -f "$CONFIG" ]] ; then
    # Copy the default config over
    cp /package/production.ini "$CONFIG"
    # Change default settings
    : ${SQLALCHEMY_URL:=sqlite:////fietsboek/database/fietsboek.sqlite}
    sed -i '/^sqlalchemy\.url = /c sqlalchemy.url = '"$SQLALCHEMY_URL" "$CONFIG"

    if [[ ! -v REDIS_URL ]] ; then
        error "need REDIS_URL set"
        exit 1
    fi
    sed -i '/^\[app:main\]/a redis.url = '"$REDIS_URL" "$CONFIG"

    : ${DATA_DIR:=/fietsboek/data}
    mkdir -p "$DATA_DIR"
    sed -i '/^\[app:main\]/a fietsboek.data_dir = '"$DATA_DIR" "$CONFIG"

    : ${SESSION_KEY:=$(openssl rand -hex 20)}
    sed -i '/^session_key = /c session_key = '"$SESSION_KEY" "$CONFIG"

    sed -i '/^\[app:main\]/a fietsboek.pages = /fietsboek/pages' "$CONFIG"

    : ${ENABLE_ACCOUNT_REGISTRATION:=true}
    sed -i '/^enable_account_registration =/c enable_account_registration = '"$ENABLE_ACCOUNT_REGISTRATION" "$CONFIG"

    if [[ -v DEFAULT_LOCALE_NAME ]] ; then
        sed -i '/^pyramid\.default_locale_name =/c pyramid.default_locale_name = '"$DEFAULT_LOCALE_NAME" "$CONFIG"
    fi

    if [[ -v EMAIL_FROM ]] ; then
        sed -i '/^email\.from =/c email.from = '"$EMAIL_FROM" "$CONFIG"
    fi
    if [[ -v EMAIL_SMTP_URL ]] ; then
        sed -i '/^email\.smtp_url =/c email.smtp_url = '"$EMAIL_SMTP_URL" "$CONFIG"
    fi
    if [[ -v EMAIL_USERNAME ]] ; then
        sed -i '/^email\.username =/c email.username = '"$EMAIL_USERNAME" "$CONFIG"
    fi
    if [[ -v EMAIL_PASSWORD ]] ; then
        sed -i '/^email\.password =/c email.password = '"$EMAIL_PASSWORD" "$CONFIG"
    fi

    if [[ -v LOGLEVEL ]] ; then
        # We are only changing the fietsboek log level here, as SQLAlchemy
        # produces a lot of noise.
        sed -i '/\[logger_fietsboek\]/{N;s/level = .*/level = '"$LOGLEVEL"'/}' "$CONFIG"
    fi
fi

# Make sure the data schema is up to date, or rather initialize it if this is
# the first time
(cd /package && fietsupdate update -fc "$CONFIG")

exec "$@"