#!/bin/bash
# Launch a Claude Code container with the current directory mounted as a volume
# Syntax:  claudes.sh [--no-cache] [--yolo|--no-yolo] [--no-exit] [--rc] [claude options...]
#          claudes.sh --list-images
#          claudes.sh --clean-images
#          claudes.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 claudes.sh is launched from)
# --yolo:    run claude with the option --dangerously-skip-permissions
# --no-yolo: run claude without the option --dangerously-skip-permissions (it is the default)
# --rc:      run claude in Remote Control mode (claude remote-control), with the permission
#            mode auto for the spawned sessions (bypassPermissions if --yolo is provided)
#            (rc, without the dashes, is still accepted as an alias)
# --no-exit: stay into the container with a bash shell after claude has ended
#            (by default, when claude is terminated, the container is terminated too)
# --list-images: only list the docker images generated by claudes.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 claudes.sh and remove the obsolete
#            ones (previous builds), without building nor running the container
#            (the containers still using an obsolete image are stopped and removed first)
# Other arguments are passed to claude (for example: claudes.sh --continue).
#
# The configuration directory ~/.claude of the host (credentials, settings,
# memory, sessions) is shared with the container (see README.md).
#
# 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.

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

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

Usage: $(basename "$0") [--no-cache] [--yolo|--no-yolo] [--no-exit] [--rc] [claude options...]
       $(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.
  --yolo           Run claude with the option --dangerously-skip-permissions.
  --no-yolo        Run claude without the option --dangerously-skip-permissions (it is the default).
  --rc             Run claude in Remote Control mode (claude remote-control), with the permission
                   mode auto for the spawned sessions (bypassPermissions if --yolo is provided).
  --no-exit        Stay into the container with a bash shell after claude has ended
                   (by default, the container is terminated when claude 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.
                   The containers still using an obsolete image are stopped and removed first.
  -h, --help       Show this help and exit.
The other arguments are passed to claude (for example: $(basename "$0") --continue).

Environment variables:
  ANTHROPIC_API_KEY        API key passed to claude (otherwise ~/.claude/.credentials.json is used).
  CLAUDE_CODE_OAUTH_TOKEN  OAuth token passed to claude (otherwise ~/.claude/.credentials.json is used).
  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-claude build directory), whatever the current
# directory is. Symbolic links are resolved so a link to claudes.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 the docker-claude directory and
# the files shared with docker-vibe (open-on-host, xdg-open-shim, smtpblock.sh, sendmail-stub, bashrc-prompt).
# 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 claudes.sh is launched from. The tar is reproducible (sorted, no date nor owner) so it can be hashed.
# claudes.sh and README.md are excluded: they are not used by the Dockerfile, so editing them must not trigger a build.
CONTEXT_TAR_ARGS=(. -C "$SCRIPT_DIR/../docker-vibe" open-on-host xdg-open-shim smtpblock.sh sendmail-stub bashrc-prompt)

# Output the tar of the build context
build_context() {
    tar -cf - --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner --exclude=./claudes.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 \"$CLAUDES_HASH_LABEL\" }}" docker-claude 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 claudes.sh are found with the label set at build, or for the images built
# before this label existed, with the BROWSER and DISABLE_AUTOUPDATER variables both set by the Dockerfile
# (BROWSER alone is not enough, docker-vibe sets the same). They are listed, then removed with --clean-images.
# An image still used by a container (started before the last rebuild) can not be removed, even with
# docker rmi -f: the containers using an obsolete image are stopped and removed first.
if [ "$LIST_IMAGES" -eq 1 ] || [ "$CLEAN_IMAGES" -eq 1 ]; then
    echo "------------------------------------------------------------"
    echo "Current image generated by claudes.sh:"
    sudo docker images --format 'table {{.ID}}\t{{.Repository}}:{{.Tag}}\t{{.CreatedSince}}\t{{.Size}}' docker-claude
    echo "Build context: $SCRIPT_DIR + shared files of $(cd "$SCRIPT_DIR/../docker-vibe" && pwd)"
    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 \
            | awk -v label="\"$CLAUDES_LABEL\":\"1\"" 'index($0, label) || (index($0, "\"BROWSER=/usr/local/bin/open-on-host\"") && index($0, "\"DISABLE_AUTOUPDATER=1\"")) { print $1 }')
    fi

    echo
    echo "Obsolete images generated by claudes.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-claude), then stop without removing anything.
    if [ "$CLEAN_IMAGES" -eq 0 ]; then
        ANCESTOR_FILTERS=(--filter "ancestor=docker-claude")
        for OBSOLETE_ID in "${OBSOLETE_IDS[@]}"; do
            ANCESTOR_FILTERS+=(--filter "ancestor=$OBSOLETE_ID")
        done
        echo
        echo "Containers using an image generated by claudes.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 (and stop the containers using them): $(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 container can not be removed, even with docker rmi -f: stop and
        # remove the containers using an obsolete image first (the containers started by claudes.sh
        # use --rm, so stopping them removes them).
        ANCESTOR_FILTERS=()
        for OBSOLETE_ID in "${OBSOLETE_IDS[@]}"; do
            ANCESTOR_FILTERS+=(--filter "ancestor=$OBSOLETE_ID")
        done
        CONTAINER_IDS=$(sudo docker ps -a --quiet "${ANCESTOR_FILTERS[@]}")
        if [ -n "$CONTAINER_IDS" ]; then
            echo "Containers still using an obsolete image (stopped, then removed):"
            sudo docker ps -a --format 'table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}' "${ANCESTOR_FILTERS[@]}"
            echo
            # shellcheck disable=SC2086
            sudo docker stop $CONTAINER_IDS 2>/dev/null || true
            # shellcheck disable=SC2086
            sudo docker rm -f $CONTAINER_IDS 2>/dev/null || true
        fi
        if ! sudo docker rmi "${OBSOLETE_IDS[@]}"; then
            echo "Some images were not removed (still used by a 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 Claude Code 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-claude is up to date with the build context (${CONTEXT_HASH:0:12}), it is used without build."
    echo "Use --no-cache to rebuild it (for example to get a new version of Claude Code)."
elif ! build_context | sudo docker build -t docker-claude --label "$CLAUDES_LABEL=1" --label "$CLAUDES_HASH_LABEL=$CONTEXT_HASH" "${BUILD_ARGS[@]}" -; then
    echo "ERROR: Build of the docker-claude 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.
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

# 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-vibe, where pre-commit is installed differently (environments may not be compatible).
PRE_COMMIT_CACHE_DIR="$HOME/.cache/docker-claude/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 Claude Code can read
# the clipboard of the host (xclip on the X server or XWayland, wl-paste) 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 claudes.sh is started outside a graphical session: Claude Code 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 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

# 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 links opened by claude (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

# Share the Claude Code configuration of the host (credentials, settings, plugins,
# memory and sessions of the projects) with the container. It is mounted at the
# same path, so the absolute paths it contains stay valid. The state file
# ~/.claude.json (MCP servers, projects...) is replaced at each write, so it can
# not be bind mounted safely: into the container, ~/.claude.json is a link to
# ~/.claude/.claude.json (see docker-entrypoint.sh). The state file of the host is
# copied there at each launch, so the container gets the MCP servers of the host
# (the changes made into the container are lost at the next launch).
mkdir -p "$HOME/.claude"
if [ -f "$HOME/.claude.json" ] && [ ! -L "$HOME/.claude.json" ]; then
    echo "Copy $HOME/.claude.json into $HOME/.claude/.claude.json"
    cp -p "$HOME/.claude.json" "$HOME/.claude/.claude.json"
fi
CLAUDE_ENV_ARGS=()
# Pass the API key or the OAuth token of the host when one is set (otherwise the
# credentials of ~/.claude/.credentials.json are used).
# DOCKER_ALLOW_SMTP=1 starts the container without the block of the outbound SMTP ports.
# TERM and COLORTERM give the color support of the host terminal (docker sets TERM=xterm by default,
# so Claude Code would fall back to 16 colors and display, for example, its orange logo in red).
for VAR in ANTHROPIC_API_KEY CLAUDE_CODE_OAUTH_TOKEN DOCKER_ALLOW_SMTP TERM COLORTERM; do
    VAR_VALUE=$(printenv "$VAR" || true)
    if [ -n "$VAR_VALUE" ]; then
        CLAUDE_ENV_ARGS+=(-e "$VAR=$VAR_VALUE")
    fi
done

# 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[@]}" \
  "${TEST_ARGS[@]}" \
  "${LOG_ARGS[@]}" \
  "${TX_ARGS[@]}" \
  "${SECURITY_ARGS[@]}" \
  "${CLAUDE_ENV_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/.claude,dst=$HOME/.claude" \
  "${HOME_MOUNTS[@]}" \
  -w "$WORK_DIR" \
  docker-claude "${ARGS[@]}"
