#!/bin/bash
# Launch a vibe container with the current directory mounted as a volume
# Syntax:  vibes.sh [--no-cache] [--no-yolo] [--no-exit]
#          vibes.sh --list-images
#          vibes.sh --clean-images
#          vibes.sh --help
# --no-cache: rebuild the docker image without using the docker build cache
#            (without it, the image is built only when the files used by the Dockerfile have changed since the
#            last build, and the last image built is used whatever the directory vibes.sh is launched from)
# --no-yolo: run vibe without the --yolo option (--yolo is the default)
# --no-exit: stay into the container with a bash shell after vibe has ended
#            (by default, when vibe is terminated, the container is terminated too)
# --list-images: only list the docker images generated by vibes.sh (the current one, with its status against
#            the build context, and the obsolete ones) and the containers using them, without removing anything
# --clean-images: only list the docker images generated by vibes.sh and remove the obsolete
#            ones (previous builds), without building nor running the container
#
# When the current directory is not the Dolibarr core sources (the first line of
# its README.md file is not "# DOLIBARR ERP & CRM"), the directory dolibarr_dev or dolibarr found
# next to the current directory is also mounted into the container, so the
# Dolibarr sources are available into the container at the same path as on the host.
# When it is the Dolibarr core sources without a documents directory, the directory
# dolibarr_documents found next to it (when it exists) is mounted as its documents directory.

# Label set on the images built by vibes.sh, so --clean-images can find them
VIBES_LABEL="org.dolibarr.docker-vibe"
# Label storing the hash of the build context of the image, to reuse it without build when the context is unchanged
VIBES_HASH_LABEL="org.dolibarr.docker-vibe.context-hash"

# Print the possible options of this script
print_usage() {
    cat <<EOF
Launch a vibe container with the current directory mounted as a volume.

Usage: $(basename "$0") [--no-cache] [--no-yolo] [--no-exit]
       $(basename "$0") --list-images
       $(basename "$0") --clean-images
       $(basename "$0") --help

Options:
  --no-cache       Rebuild the docker image without using the docker build cache.
                   Without it, the image is built only when the files used by the Dockerfile have
                   changed since the last build: the last image built is used whatever the directory.
  --no-yolo        Run vibe without the --yolo option (--yolo is the default).
  --no-exit        Stay into the container with a bash shell after vibe has ended
                   (by default, the container is terminated when vibe is terminated).
  --list-images    Only list the docker images generated by $(basename "$0") (the current one, with
                   its status against the build context, and the obsolete ones) and the containers
                   using them, without building, running nor removing anything.
  --clean-images   Only list the docker images generated by $(basename "$0") and remove the
                   obsolete ones (previous builds), without building nor running the container.
  -h, --help       Show this help and exit.

Environment variables:
  DOCKER_ALLOW_SMTP=1      Start the container without the block of the outbound SMTP ports.
  DOL_CTI_ADMIN_LOGIN      Login used by the Dolibarr PHPUnit REST API and login tests.
  DOL_CTI_ADMIN_PASSWORD   Password used by the Dolibarr PHPUnit REST API and login tests.
EOF
}

# Extract --no-cache flag from arguments (consumed by docker build, not passed to container)
# and --list-images, --clean-images and --help (consumed by this script).
BUILD_ARGS=()
ARGS=()
LIST_IMAGES=0
CLEAN_IMAGES=0
for arg in "$@"; do
  if [[ "$arg" == "--help" || "$arg" == "-h" ]]; then
    print_usage
    exit 0
  elif [[ "$arg" == "--no-cache" ]]; then
    BUILD_ARGS+=(--no-cache)
  elif [[ "$arg" == "--list-images" ]]; then
    LIST_IMAGES=1
  elif [[ "$arg" == "--clean-images" ]]; then
    CLEAN_IMAGES=1
  else
    ARGS+=("$arg")
  fi
done

# Directory containing this script (the docker-vibe build directory), whatever the current
# directory is. Symbolic links are resolved so a link to vibes.sh (in ~/bin for example) works too.
SCRIPT_DIR=$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)

# Build context of the image
# The build context is created on the fly: it contains only the docker-vibe directory. It does not depend on the
# repository nor on the current directory (the .pre-commit-config.yaml is not included, the pre-commit hooks are
# kept into a cache of the host, see PRE_COMMIT_CACHE_DIR), so the image is the same whatever the directory vibes.sh
# is launched from. The tar is reproducible (sorted, no date nor owner) so it can be hashed.
# vibes.sh and README.md are excluded: they are not used by the Dockerfile, so editing them must not trigger a build.
CONTEXT_TAR_ARGS=(.)

# Output the tar of the build context
build_context() {
    tar -cf - --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner --exclude=./vibes.sh --exclude=./README.md -C "$SCRIPT_DIR" "${CONTEXT_TAR_ARGS[@]}"
}

# The hash of the build context is stored as a label of the image. When the image was already built from the same
# context (from any directory), it is used without build: after a rebuild with --no-cache, the containers launched
# later from the other directories use this last image.
CONTEXT_HASH=$(build_context | sha256sum | cut -d ' ' -f 1)
IMAGE_HASH=$(sudo docker image inspect --format "{{ index .Config.Labels \"$VIBES_HASH_LABEL\" }}" docker-vibe 2>/dev/null || true)

# Options --list-images and --clean-images: each rebuild with changes leaves the previous image untagged (dangling).
# The dangling images generated by vibes.sh are found with the label set at build, or for the images built
# before this label existed, with the PATH starting with /opt/vibe/bin set by the Dockerfile (the BROWSER
# variable can't be used, docker-claude sets the same). They are listed, then removed with --clean-images.
if [ "$LIST_IMAGES" -eq 1 ] || [ "$CLEAN_IMAGES" -eq 1 ]; then
    echo "------------------------------------------------------------"
    echo "Current image generated by vibes.sh:"
    sudo docker images --format 'table {{.ID}}\t{{.Repository}}:{{.Tag}}\t{{.CreatedSince}}\t{{.Size}}' docker-vibe
    echo "Build context: $SCRIPT_DIR"
    IMAGE_HASH_SHORT=${IMAGE_HASH:0:12}
    if [ "$IMAGE_HASH" = "$CONTEXT_HASH" ]; then
        echo "Up to date with the build context (${CONTEXT_HASH:0:12}): the next launches use it without build."
    else
        echo "Not up to date with the build context (image: ${IMAGE_HASH_SHORT:-none}, context: ${CONTEXT_HASH:0:12}): the next launch builds it."
    fi

    OBSOLETE_IDS=()
    DANGLING_IDS=$(sudo docker images --quiet --no-trunc --filter dangling=true | sort -u)
    if [ -n "$DANGLING_IDS" ]; then
        # shellcheck disable=SC2086
        mapfile -t OBSOLETE_IDS < <(sudo docker image inspect --format '{{.Id}} {{json .Config.Labels}} {{json .Config.Env}}' $DANGLING_IDS \
            | grep -F -e "\"$VIBES_LABEL\":\"1\"" -e '"PATH=/opt/vibe/bin:' | cut -d ' ' -f 1)
    fi

    echo
    echo "Obsolete images generated by vibes.sh: ${#OBSOLETE_IDS[@]}"
    if [ "${#OBSOLETE_IDS[@]}" -gt 0 ]; then
        sudo docker images --no-trunc --filter dangling=true --format '{{.ID}}\t{{.CreatedSince}}\t{{.Size}}' | grep -F -f <(printf '%s\n' "${OBSOLETE_IDS[@]}")
    fi

    # Option --list-images: also list the containers using these images (a container started before the last
    # rebuild shows the ID of its obsolete image instead of docker-vibe), then stop without removing anything.
    if [ "$CLEAN_IMAGES" -eq 0 ]; then
        ANCESTOR_FILTERS=(--filter "ancestor=docker-vibe")
        for OBSOLETE_ID in "${OBSOLETE_IDS[@]}"; do
            ANCESTOR_FILTERS+=(--filter "ancestor=$OBSOLETE_ID")
        done
        echo
        echo "Containers using an image generated by vibes.sh:"
        sudo docker ps -a --format 'table {{.ID}}\t{{.Image}}\t{{.RunningFor}}\t{{.Status}}\t{{.Names}}' "${ANCESTOR_FILTERS[@]}"
        echo
        echo "To remove the obsolete images: $(basename "$0") --clean-images"
        exit 0
    fi

    if [ "${#OBSOLETE_IDS[@]}" -gt 0 ]; then
        echo
        echo "Remove the obsolete images..."
        # An image still used by a running container (started before the last rebuild) is not removed.
        if ! sudo docker rmi "${OBSOLETE_IDS[@]}"; then
            echo "Some images were not removed (still used by a running container ?)."
        fi
    fi

    echo
    sudo docker system df
    echo
    echo "Note: the docker build cache is not removed (it is shared by all the docker builds of the host)."
    echo "To remove it too: sudo docker builder prune"
    exit 0
fi

echo "Launch the docker VM with Vibe harness for AI"

# Detect if the current directory is the Dolibarr core sources (the first line of
# the README.md file is "# DOLIBARR ERP & CRM"): in that case it is already mounted
# as the working directory and no other dolibarr directory must be mounted.
IS_DOLIBARR_CORE=0
if [ -f README.md ] && [ "$(head -n 1 README.md | tr -d '\r')" = "# DOLIBARR ERP & CRM" ]; then
    IS_DOLIBARR_CORE=1
fi
# Previous detection, using the git remote (github.com/Dolibarr/dolibarr, or a fork of it:
# any remote pointing to a repository named "dolibarr")
#if git remote -v 2>/dev/null | grep origin | awk '{print $2}' | sed -e 's/\.git$//' -e 's#.*/##' | grep -qix dolibarr; then
#    IS_DOLIBARR_CORE=1
#fi

echo IS_DOLIBARR_CORE="$IS_DOLIBARR_CORE"
echo DOL_CTI_ADMIN_LOGIN="$DOL_CTI_ADMIN_LOGIN"
echo DOL_CTI_ADMIN_PASSWORD="${DOL_CTI_ADMIN_PASSWORD:0:3}..."

GH_TOKEN=$(gh auth token)
if [ -z "$GH_TOKEN" ]; then
    echo "GH_TOKEN is not set."
else
	echo GH_TOKEN="${GH_TOKEN:0:4}...${GH_TOKEN: -4}"
fi

set -o errexit
set -o nounset
set -o pipefail

# Build image (only when the image is missing or built from another build context, see CONTEXT_HASH above)
if [ "${#BUILD_ARGS[@]}" -eq 0 ] && [ "$IMAGE_HASH" = "$CONTEXT_HASH" ]; then
    echo "The image docker-vibe is up to date with the build context (${CONTEXT_HASH:0:12}), it is used without build."
    echo "Use --no-cache to rebuild it."
elif ! build_context | sudo docker build -t docker-vibe --label "$VIBES_LABEL=1" --label "$VIBES_HASH_LABEL=$CONTEXT_HASH" "${BUILD_ARGS[@]}" -; then
    echo "ERROR: Build of the docker-vibe image failed."
    echo "The container is not started to avoid running an outdated image."
    exit 1
fi

# Run image
GIT_DIR=$(basename "$PWD")
export GIT_DIR

# Directory mounted as the working directory: ~/git/GIT_DIR (development context). When it does not exist
# (production context, sources outside of ~/git), the current directory is mounted at the same path.
WORK_DIR="$HOME/git/$GIT_DIR"
if [ ! -d "$WORK_DIR" ]; then
    WORK_DIR="$PWD"
fi

# Files of the host home directory mounted only when they exist (production context), as docker refuses
# to start with a missing bind source.
mkdir -p "$HOME/.vibe"
HOME_MOUNTS=()
for HOME_FILE in .gitconfig .bash_history; do
    if [ -f "$HOME/$HOME_FILE" ]; then
        HOME_MOUNTS+=(--mount "type=bind,src=$HOME/$HOME_FILE,dst=$HOME/$HOME_FILE")
    fi
done

# When working on something else than the Dolibarr core (a module for example),
# also mount the sibling directory dolibarr_dev or dolibarr (in this order of
# preference) when it exists next to the current directory.
EXTRA_MOUNTS=()
if [ "$IS_DOLIBARR_CORE" -eq 0 ]; then
    PARENT_DIR=$(dirname "$PWD")
    for DOLIBARR_DIR in dolibarr_dev dolibarr; do
        if [ -d "$PARENT_DIR/$DOLIBARR_DIR" ]; then
            EXTRA_MOUNTS+=(--mount "type=bind,src=$PARENT_DIR/$DOLIBARR_DIR,dst=$PARENT_DIR/dolibarr")
            break
        fi
    done
fi

# When working on the Dolibarr core without a documents directory into the working directory,
# mount the sibling directory dolibarr_documents (when it exists) as the documents directory.
# An empty documents directory is the mount point left by a previous run, so it is reused.
if [ "$IS_DOLIBARR_CORE" -eq 1 ]; then
    DOCUMENTS_DIR="$(dirname "$WORK_DIR")/dolibarr_documents"
    if [ -d "$DOCUMENTS_DIR" ] && [ ! -L "$WORK_DIR/documents" ]; then
        if [ ! -e "$WORK_DIR/documents" ] || { [ -d "$WORK_DIR/documents" ] && [ -z "$(ls -A "$WORK_DIR/documents")" ]; }; then
            echo "Mount $DOCUMENTS_DIR as $WORK_DIR/documents"
            EXTRA_MOUNTS+=(--mount "type=bind,src=$DOCUMENTS_DIR,dst=$WORK_DIR/documents")
        fi
    fi
fi

# Dedicated directory for the documents produced by the AI agent and shared with the host
# (reports, slides, graphs, exports, ...): it is mounted into the container at the same path.
# The directory is created when missing, docker refusing a bind mount with a missing source.
# /tmp is purged at reboot: the documents must be taken out of the host before.
AGENTS_DOCUMENTS_DIR=/tmp/agents_documents
mkdir -p "$AGENTS_DOCUMENTS_DIR"
EXTRA_MOUNTS+=(--mount "type=bind,src=$AGENTS_DOCUMENTS_DIR,dst=$AGENTS_DOCUMENTS_DIR")

# Cache of the pre-commit hooks environments (PRE_COMMIT_HOME of the image), kept on the host: the hooks of a
# revision are downloaded at their first use, then reused by all the next containers, whatever the repository.
# It is not shared with docker-claude, where pre-commit is installed differently (environments may not be compatible).
PRE_COMMIT_CACHE_DIR="$HOME/.cache/docker-vibe/pre-commit"
mkdir -p "$PRE_COMMIT_CACHE_DIR"
EXTRA_MOUNTS+=(--mount "type=bind,src=$PRE_COMMIT_CACHE_DIR,dst=/var/cache/pre-commit")

# Pass the host graphical session to the container so that Vibe can copy to
# the clipboard of the host (pyperclip/xclip on the X server or XWayland) and
# open links in the browser of the host (open-on-host through the D-Bus
# session bus and the xdg-desktop-portal, see README.md). Nothing is added
# when vibes.sh is started outside a graphical session: Vibe then falls back
# to its own mechanisms (OSC 52, host terminal selection with Shift).
GRAPHIC_ARGS=()
for VAR in DISPLAY WAYLAND_DISPLAY XDG_SESSION_TYPE XDG_RUNTIME_DIR XAUTHORITY; do
    VAR_VALUE=$(printenv "$VAR" || true)
    if [ -n "$VAR_VALUE" ]; then
        GRAPHIC_ARGS+=(-e "$VAR=$VAR_VALUE")
    fi
done
if [ -d /tmp/.X11-unix ]; then
    GRAPHIC_ARGS+=(--mount "type=bind,src=/tmp/.X11-unix,dst=/tmp/.X11-unix")
fi
if [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -d "${XDG_RUNTIME_DIR}" ]; then
    # Contains the Wayland socket, the D-Bus session bus socket and the
    # XWayland authorization cookie of the host session.
    GRAPHIC_ARGS+=(--mount "type=bind,src=${XDG_RUNTIME_DIR},dst=${XDG_RUNTIME_DIR}")
fi
if [ -z "${XAUTHORITY:-}" ] && [ -f "$HOME/.Xauthority" ]; then
    # X11 session without XAUTHORITY exported: the cookie is in ~/.Xauthority.
    GRAPHIC_ARGS+=(-e "XAUTHORITY=$HOME/.Xauthority" --mount "type=bind,src=$HOME/.Xauthority,dst=$HOME/.Xauthority")
fi

# Pass the audio session of the host to the container so that the voice
# features of Vibe (microphone capture and speech playback through the
# PortAudio library installed into the image) work into the container:
# the container has no sound card, PortAudio must reach the audio server
# (PulseAudio, or PipeWire that provides the same socket) of the host
# session. The socket lives into XDG_RUNTIME_DIR, already mounted and
# passed by the graphic section above, PULSE_SERVER points PortAudio at
# it and the PulseAudio cookie of the host is mounted read-only so the
# server accepts the connection. Nothing is added outside a session with
# an audio server: Vibe then disables its voice features.
AUDIO_ARGS=()
if [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -S "${XDG_RUNTIME_DIR}/pulse/native" ]; then
    AUDIO_ARGS+=(-e "PULSE_SERVER=unix:${XDG_RUNTIME_DIR}/pulse/native")
    if [ -d "$HOME/.config/pulse" ]; then
        AUDIO_ARGS+=(--mount "type=bind,src=$HOME/.config/pulse,dst=$HOME/.config/pulse,readonly")
    fi
fi

# Pass the Dolibarr PHPUnit credentials to the container: the REST API tests
# (test/phpunit/AbstractRestAPITest.php) and SecurityLoginTest.php use them to
# log in with a dedicated account instead of the admin/admin default.
# Nothing is added when the variables are not set on the host.
TEST_ARGS=()
for VAR in DOL_CTI_ADMIN_LOGIN DOL_CTI_ADMIN_PASSWORD; do
    VAR_VALUE=$(printenv "$VAR" || true)
    if [ -n "$VAR_VALUE" ]; then
        TEST_ARGS+=(-e "$VAR=$VAR_VALUE")
    fi
done

# DOCKER_ALLOW_SMTP=1 starts the container without the block of the outbound SMTP ports.
if [ "${DOCKER_ALLOW_SMTP:-}" = "1" ]; then
    TEST_ARGS+=(-e "DOCKER_ALLOW_SMTP=1")
fi

# Make the Apache logs of the host readable into the container (read-only mount).
# The GID owning the directory (adm on Debian/Ubuntu) is passed so the entrypoint
# can add the user to this group, as the directory is not readable by others.
LOG_ARGS=()
if [ -d /var/log/apache2 ]; then
    LOG_ARGS+=(-e "HOST_APACHE_LOG_GID=$(stat -c %g /var/log/apache2)" --mount "type=bind,src=/var/log/apache2,dst=/var/log/apache2,readonly")
fi
# Same for the mail logs of the host (MTA, PHP mail() and PHP sendmail wrapper), each file being mounted only
# when it exists on the host. The GIDs owning them are passed so the entrypoint can add the user to these groups.
# The mount follows the file, not its name: after a rotation on the host, the container still sees the old file.
MAIL_LOG_GIDS=()
for MAIL_LOG_FILE in /var/log/mail.log /var/log/phpmail.log /var/log/phpsendmail.log; do
    if [ -f "$MAIL_LOG_FILE" ]; then
        LOG_ARGS+=(--mount "type=bind,src=$MAIL_LOG_FILE,dst=$MAIL_LOG_FILE,readonly")
        MAIL_LOG_GIDS+=("$(stat -c %g "$MAIL_LOG_FILE")")
    fi
done
if [ "${#MAIL_LOG_GIDS[@]}" -gt 0 ]; then
    LOG_ARGS+=(-e "HOST_MAIL_LOG_GIDS=${MAIL_LOG_GIDS[*]}")
fi
echo "LOG_ARGS=${LOG_ARGS[*]}"

# Share the Transifex credentials of the host with the tx client of the container (read-only mount).
TX_ARGS=()
if [ -f "$HOME/.transifexrc" ]; then
    TX_ARGS+=(--mount "type=bind,src=$HOME/.transifexrc,dst=$HOME/.transifexrc,readonly")
fi

# The AppArmor mediation of the dbus-daemon of the host refuses the connections
# coming from the default docker profile (docker-default declares no dbus rule),
# so the clicks on the chat links (open-on-host, see README.md) are ignored
# without it. Run the container unconfined so its processes may talk to the
# D-Bus session bus of the host. Only added when AppArmor is enabled on the
# host (the option makes docker fail on the hosts without AppArmor).
SECURITY_ARGS=()
if [ "$(cat /sys/module/apparmor/parameters/enabled 2>/dev/null)" = "Y" ]; then
    SECURITY_ARGS+=(--security-opt apparmor=unconfined)
fi

# The cgroup path of the container must be seen the same way from inside the container
# and by the kernel, so docker-entrypoint.sh can install an iptables rule scoped to the
# only container instead of blocking the SMTP ports of the whole machine (see smtpblock.sh).
# --cgroupns=host is required for that: with the private cgroup namespace of docker, the
# path read from /proc/self/cgroup into the container is not the one known by the kernel.

sudo docker run --rm -it \
  -e HOST_UID="$(id -u)" \
  -e HOST_GID="$(id -g)" \
  -e HOST_USER="$(id -un)" \
  -e HOST_GROUP="$(id -un)" \
  -e GH_TOKEN="$GH_TOKEN" \
  "${GRAPHIC_ARGS[@]}" \
  "${AUDIO_ARGS[@]}" \
  "${TEST_ARGS[@]}" \
  "${LOG_ARGS[@]}" \
  "${TX_ARGS[@]}" \
  "${SECURITY_ARGS[@]}" \
  --network=host \
  --cgroupns=host \
  --cap-add=NET_ADMIN \
  --mount "type=bind,src=/var/run/mysqld/mysqld.sock,dst=/var/run/mysqld/mysqld.sock" \
  --mount "type=bind,src=$WORK_DIR,dst=$WORK_DIR" \
  "${EXTRA_MOUNTS[@]}" \
  --mount "type=bind,src=$HOME/.vibe,dst=/home/$(id -un)/.vibe" \
  "${HOME_MOUNTS[@]}" \
  -w "$WORK_DIR" \
  docker-vibe "${ARGS[@]}"
