#!/bin/bash

cd /app

echo "Installing Bun Dependencies ..."
bun update -g
bun install
bun update @moduletrace/datasquirel
echo "Bun Dependencies Installed Successfully!"

bun init/init-sql/index.ts

if [[ $? == 0 ]]; then
    echo "Dsql Database config complete"
else
    echo "Dsql Database configuration failed. Exiting ..."
    exit 1
fi

bun init/init-db/index.ts

if [[ $? == 0 ]]; then
    echo "Dsql Schema Setup Complete"
else
    echo "Dsql Schema Setup failed. Exiting ..."
    exit 1
fi

if [ -n "${NEXT_PUBLIC_DSQL_LOCAL}" ]; then
    if [[ "$DSQL_HOST_ENV" == *"dev_dev"* ]]; then
        echo "NEXT_PUBLIC_DSQL_LOCAL is set in dev environment."
        batchrun
    else
        echo "NEXT_PUBLIC_DSQL_LOCAL is set. Running Local initialization ..."
        bun start
    fi
else
    echo "NEXT_PUBLIC_DSQL_LOCAL is not set."

    if [ "${DSQL_HOST_ENV}" == "prod_prod" ]; then
        echo "Main Production Environment"
        buncid
    else
        echo "Dev Environment"
        batchrun
    fi
fi
