#!/usr/bin/env bash
set -Eeuo pipefail

SCRIPT_NAME="$(basename "$0")"
BASE_DIR="$PWD"
DRY_RUN=0
LAB_NAME=""

usage() {
    cat <<'EOF'
Usage: lab-init.sh NAME [options]

Create a small, repeatable lab workspace without overwriting existing files.

Options:
  --base-dir DIR  Parent directory for the lab (default: current directory).
  --dry-run       Print planned changes without creating files.
  -h, --help      Show this help.
EOF
}

while (( $# > 0 )); do
    case "$1" in
        --base-dir)
            (( $# >= 2 )) || { echo "--base-dir requires a value." >&2; exit 2; }
            BASE_DIR="$2"
            shift
            ;;
        --dry-run) DRY_RUN=1 ;;
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            echo "Unknown option: $1" >&2
            exit 2
            ;;
        *)
            [[ -z "$LAB_NAME" ]] || { echo "Only one lab name is allowed." >&2; exit 2; }
            LAB_NAME="$1"
            ;;
    esac
    shift
done

[[ -n "$LAB_NAME" ]] || { usage >&2; exit 2; }
case "$LAB_NAME" in
    /*|*..*|*/*|*\\*) echo "Use a simple lab name without paths or '..'." >&2; exit 2 ;;
esac

LAB_DIR="$BASE_DIR/$LAB_NAME"
DIRS=(scans notes evidence loot www tmp)
FILES=(scope.txt hosts.txt credentials.txt todo.md)

run() {
    printf '+'
    printf ' %q' "$@"
    printf '\n'
    (( DRY_RUN == 1 )) || "$@"
}

run mkdir -p "$LAB_DIR"
for dir in "${DIRS[@]}"; do
    run mkdir -p "$LAB_DIR/$dir"
done

for file in "${FILES[@]}"; do
    path="$LAB_DIR/$file"
    if [[ -e "$path" ]]; then
        printf '[%s] Existing file left unchanged: %s\n' "$SCRIPT_NAME" "$path"
    elif (( DRY_RUN == 1 )); then
        printf '+ create %q\n' "$path"
    else
        : > "$path"
    fi
done

printf '[%s] Lab workspace ready: %s\n' "$SCRIPT_NAME" "$LAB_DIR"
