#!/bin/bash
set -eu

mkdir -p /app/data/library /app/data/config /app/data/assets /app/data/resources
mkdir -p /tmp/vite-temp /tmp/vite /tmp/cache

CONFIG_TEMPLATE_FILE="/app/pkg/config.yml.template"
CONFIG_FILE="/app/data/config/config.yml"

# Check if config file exists in /app/data/config
if [ -f "$CONFIG_FILE" ]; then
    echo "config.yml already exists in $CONFIG_FILE"
else
    # Copy the template to the target location
    echo "Copying $CONFIG_TEMPLATE_FILE to $CONFIG_FILE"
    cp "$CONFIG_TEMPLATE_FILE" "$CONFIG_FILE"

    # Add in TURN
    readonly time=$(date +%s)
    readonly expiry=512640 # one year in seconds
    export turn_username=$(( $time + $expiry ))
    export turn_password=$(echo -n $turn_username | openssl dgst -binary -sha1 -hmac ${CLOUDRON_TURN_SECRET} | openssl base64)

    envsubst < $CONFIG_TEMPLATE_FILE > $CONFIG_FILE

    echo "Successfully created $CONFIG_FILE from template"
fi

# ensure that data directory is owned by 'cloudron' user
chown -R cloudron:cloudron /app/data /tmp/vite-temp /tmp/vite /tmp/cache

cd /app/data

export ROMM_DB_DRIVER=postgresql
export DB_HOST=${CLOUDRON_POSTGRESQL_HOST}
export DB_PORT=${CLOUDRON_POSTGRESQL_PORT}
export DB_NAME=${CLOUDRON_POSTGRESQL_DATABASE}
export DB_USER=${CLOUDRON_POSTGRESQL_USERNAME}
export DB_PASSWD=${CLOUDRON_POSTGRESQL_PASSWORD}
export OIDC_PROVIDER=${CLOUDRON_OIDC_PROVIDER_NAME}
export OIDC_CLIENT_ID=${CLOUDRON_OIDC_CLIENT_ID}
export OIDC_CLIENT_SECRET=${CLOUDRON_OIDC_CLIENT_SECRET}
export OIDC_REDIRECT_URI="${CLOUDRON_APP_ORIGIN}/api/oauth/openid"
export OIDC_SERVER_APPLICATION_URL=${CLOUDRON_OIDC_ISSUER}
export UV_PYTHON_INSTALL_DIR=/app/code/uv
export DEV_HTTPS=false
export __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS=${CLOUDRON_APP_DOMAIN}
export XDG_CACHE_HOME=/tmp/cache
export REDIS_HOST=${CLOUDRON_REDIS_HOST}
export REDIS_PORT=${CLOUDRON_REDIS_PORT}
export ROMM_BASE_PATH=/app/data
export ROMM_TMP_PATH=/tmp

ENV_TEMPLATE_FILE="/app/pkg/env.sh.template"
ENV_FILE="/app/data/env.sh"

# Check if env.sh exists in /app/data
if [ -f "$ENV_FILE" ]; then
    echo "env.sh already exists in $ENV_FILE"
else
    # Copy the template to the target location
    echo "Copying $ENV_TEMPLATE_FILE to $ENV_FILE"
    cp "$ENV_TEMPLATE_FILE" "$ENV_FILE"
    chmod +x "$ENV_FILE"

    # Generate a new secret key using openssl
    SECRET_KEY=$(openssl rand -hex 32 2>/dev/null)
    echo "export ROMM_AUTH_SECRET_KEY=$SECRET_KEY" >> "$ENV_FILE"

    echo "Successfully created $ENV_FILE from template"
fi

source /app/data/env.sh

echo "==> Starting supervisor"
exec /usr/bin/supervisord --configuration /etc/supervisor/supervisord.conf --nodaemon -i Romm
