#!/bin/bash

# Start a command inside a pixi environment
# Works in the same way as the casa-distro "bv"
# bv should be installed in the "bin" directory of the conda
# environment directory.
# except that it has no options.
# running "bv" starts a bash shell
# running "bv command <params>" runs "command <param>" inside the
# pixi environment
# symlinks to bv are treated as the command to run: if "command" is a symlink
# to "bv", then running: "command <params>" is equivalent of running
# "bv command <params>".

if [ -x "$PIXI_PROJECT_ROOT" ]; then
    echo The bv command has been invoked inside an active Pixi project.
    echo As its role is precisely to activate the project, this is useless.
    exit 1
fi

ME=$0
# echo $ME
BV=$(realpath -- "$ME")
# echo $BV
DIR_BV=$(dirname -- "$(dirname -- "$BV")")
# echo raw BV_DIR: $DIR_BV
# travel up to the pixi root
while [ ! -f "$DIR_BV/pixi.toml" ]; do
    DIR_BV2=$(dirname -- "$DIR_BV")
    if [ "$DIR_BV2" = "$DIR_BV" ]; then
        echo "Could not find pixi.toml"
        exit 1
    fi
    DIR_BV="$DIR_BV2"
done
# echo cd $DIR_BV
SHORT_ME=$(basename -- "$ME")
OPTIONS=""
if [ "$SHORT_ME" = bv ]; then
    if [ $# -eq 0 ]; then
        SHORT_ME=bash
        OPTIONS="--noprofile --norc"
    else
        SHORT_ME=$1
        shift
        if [ "$SHORT_ME" = "bash" ]; then
            OPTIONS="--noprofile --norc"
        fi
    fi
fi
# echo "$SHORT_ME"
# cd $DIR_BV
# pixi run $SHORT_ME "$@"
# echo "bash -c 'eval \"\$(pixi shell-hook)\"; eval "$SHORT_ME" "$@"'"
# eval "$(pixi shell-hook)"

# fake pixi shell-hook

export PIXI_PROJECT_ROOT="$DIR_BV"
export PIXI_PROJECT_MANIFEST="$PIXI_PROJECT_ROOT/pixi.toml"
# TODO: read pixi.toml
export PIXI_PROJECT_VERSION="0.1.0"
export PIXI_ENVIRONMENT_NAME="default"
export PIXI_IN_SHELL="1"
export PIXI_EXE=$(which pixi)
# TODO find a parsing which doesn't require sed and grep
export PIXI_PROJECT_NAME=$(grep 'name = ' "$PIXI_PROJECT_MANIFEST" | sed s/'^name = \"\(.*\)\"$'/\\1/g)
export PIXI_PROMPT="($PIXI_PROJECT_NAME)"
export PIXI_ENVIRONMENT_PLATFORMS="linux-64"
export CONDA_PREFIX="$PIXI_PROJECT_ROOT/.pixi/envs/$PIXI_ENVIRONMENT_NAME"
export CONDA_DEFAULT_ENV="$PIXI_PROJECT_NAME"
export PATH="$CONDA_PREFIX/bin:$PATH"

for ac_script in $CONDA_PREFIX/etc/conda/activate.d/*.sh;
do
    . "$ac_script"
done

export PS1="$PIXI_PROMPT \[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

. "$PIXI_PROJECT_ROOT/activate.sh"

# echo exec "$SHORT_ME" $OPTIONS "$@"
exec "$SHORT_ME" $OPTIONS "$@"
