#!/usr/bin/env bash
# htb-session — deterministic, secret-safe tmux workspace for the active box.
set -euo pipefail
umask 077
: "${PE_CONFIG_DIR:=${XDG_CONFIG_HOME:-$HOME/.config}/pentest-env}"
# shellcheck source=../config.sh
source "$PE_CONFIG_DIR/config.sh"
export PATH="$HOME/go/bin:$HOME/.cargo/bin:$HOME/.local/bin:$PATH"
command -v tmux >/dev/null 2>&1 || { printf 'tmux is not installed\n' >&2; exit 1; }
pe_dirs_ensure
if [[ $# -gt 0 ]]; then
"$PE_BIN_DIR/pe" target use "$1" >/dev/null
fi
if [[ -s $PE_ACTIVE_DISPLAY_FILE ]]; then
target_name=$(awk -F' \\| ' '{print $1}' "$PE_ACTIVE_DISPLAY_FILE")
else
target_name=lab
fi
slug=$(printf '%s' "$target_name" | tr -cs '[:alnum:]_.-' '-' | sed 's/^-//;s/-$//')
[[ -n $slug ]] || slug=lab
session="htb-$slug"
workdir="$PE_WORKROOT/$slug"
mkdir -p "$workdir"/{nmap,scans,loot,web,exploit,notes}
chmod -R go-rwx "$workdir"
touch "$workdir/notes/notes.md"
session_shell=${SHELL:-}
if [[ ! -x $session_shell ]]; then
session_shell=$(command -v zsh || command -v bash || command -v sh)
fi
if ! tmux has-session -t "=$session" 2>/dev/null; then
tmux new-session -d -s "$session" -n recon -c "$workdir"
tmux split-window -h -p 38 -t "$session:recon" -c "$workdir"
tmux split-window -v -p 50 -t "$session:recon.2" -c "$workdir"
tmux select-pane -t "$session:recon.1"
tmux new-window -d -t "$session:" -n shell -c "$workdir"
tmux new-window -d -t "$session:" -n notes -c "$workdir" \
"$session_shell" -lc 'exec "${EDITOR:-vim}" notes/notes.md'
tmux select-window -t "$session:recon"
fi
if [[ -n ${TMUX:-} ]]; then
exec tmux switch-client -t "=$session"
else
exec tmux attach-session -t "=$session"
fi