#!/usr/bin/with-contenv bashio
# shellcheck shell=bash
set -e
set -o pipefail

port=7681
workspace="$(bashio::config 'workspace')"

if [ -z "$workspace" ] || [ "$workspace" = "null" ]; then
    workspace="$HOME/workspace"
fi

if [[ "$workspace" != /* ]]; then
    bashio::log.fatal "workspace must be an absolute path"
    exec sleep infinity
fi
if [ -L "$workspace" ]; then
    bashio::log.fatal "workspace must not be a symbolic link"
    exec sleep infinity
fi

workspace="$(realpath -m -- "$workspace")"
case "$workspace" in
    "$HOME" | "$HOME"/* | /share/* | /media/* | /mnt/* | /data/* | /config/*)
        ;;
    *)
        bashio::log.fatal "workspace must be below the persistent home, /share, /media, /mnt, /data, or /config"
        exec sleep infinity
        ;;
esac

if [ ! -e "$workspace" ]; then
    install -d -m 0750 -o abc -g abc "$workspace"
elif [ ! -d "$workspace" ]; then
    bashio::log.fatal "workspace is not a directory: $workspace"
    exec sleep infinity
fi

if ! s6-setuidgid abc test -r "$workspace" || \
    ! s6-setuidgid abc test -w "$workspace" || \
    ! s6-setuidgid abc test -x "$workspace"; then
    bashio::log.fatal "workspace must be readable, writable, and searchable by user abc: $workspace"
    exec sleep infinity
fi

export CODEX_TERMINAL_WORKSPACE="$workspace"
bashio::log.info "Starting persistent Codex terminal on Home Assistant ingress port $port"
exec s6-setuidgid abc ttyd \
    -p "$port" \
    -W \
    -O \
    -t disableLeaveAlert=true \
    -t fontSize=14 \
    /usr/local/bin/codex-terminal-shell
