#!/bin/bash

POSTGRES_HOST="${POSTGRES_HOST:-beedb}"
POSTGRES_PORT="${POSTGRES_PORT:-5432}"
POSTGRES_ADMIN_USER="${POSTGRES_ADMIN_USER:-1gtT0sf8klB9lDbYZD9}"
POSTGRES_ADMIN_PASSWORD="${POSTGRES_ADMIN_PASSWORD:-ZpSwWNafyy9GhY2gzHw}"

DB_PATH="/4server/data/contracts.db"


get_contract_info() {

    echo "get_contract_info $UUID"

    # Single CTE: the table is scanned once and all projections come from it
    while IFS="=" read -r key value; do
        if [ -n "$key" ]; then
            export "$key=$value"
        fi
    done < <(sqlite3 "$DB_PATH" "
        WITH c AS (SELECT * FROM containers WHERE UUID='$UUID' LIMIT 1)
        SELECT 'UUID='          || COALESCE(UUID,          '') FROM c UNION ALL
        SELECT 'EXPIRES='       || COALESCE(expires,       '') FROM c UNION ALL
        SELECT 'IMAGE='         || COALESCE(image,         '') FROM c UNION ALL
        SELECT 'STATUS='        || COALESCE(status,        '') FROM c UNION ALL
        SELECT 'CREATED='       || COALESCE(created,       '') FROM c UNION ALL
        SELECT 'SECRET_LIST='   || COALESCE(secret_list,   '') FROM c UNION ALL
        SELECT 'CONTAINERDBID=' || COALESCE(id,            '') FROM c UNION ALL
        SELECT 'GIT='           || COALESCE(git,           '') FROM c UNION ALL
        SELECT 'BACKUP_SLOTS='  || COALESCE(backup_slots,  '') FROM c UNION ALL
        SELECT 'HDD='           || COALESCE(hdd,           '') FROM c UNION ALL
        SELECT 'WORKERS='       || COALESCE(workers,       '') FROM c UNION ALL
        SELECT 'DOMAINS_SLOTS=' || COALESCE(domains_slots, '') FROM c;
    ")

    # Parse SECRET_LIST: backslash-separated key=value pairs (e.g. worex1=1\pswl=22)
    # - printf avoids echo interpreting escape sequences
    # - tr -d '\r\n' strips any embedded newlines the DB value may contain
    # - tr '\\' '\n' turns each backslash separator into a real newline
    # - %%=* / #*= split on the FIRST = only, so base64 values like tok=ab== are safe
    if [ -n "$SECRET_LIST" ]; then
        while IFS= read -r pair || [ -n "$pair" ]; do
            _key="${pair%%=*}"
            _value="${pair#*=}"
            if [ -n "$_key" ]; then
                export "$_key=$_value"
            fi
        done < <(printf '%s' "$SECRET_LIST" | tr -d '\r\n' | tr '\\' '\n')
    fi
    export ODOO_DB_PASSWORD=$psql
}
