#!/bin/sh
# Sitebill Community Edition — unattended installer for humans and AI agents.
#
#   curl -fsSL https://sitebillcms.com/install.sh | sh -s -- --apps sitebill.callback --json
#
# Downloads docker-compose.yml, generates passwords, starts the stack, waits until the site answers,
# installs apps from the marketplace and prints ONE result (JSON with --json): site URL, admin login
# and password. Safe to re-run: an existing installation keeps its .env and only gets the missing apps.
# Design notes (ru): docs/AGENT_INSTALL_PLAN.md in the platform repository.
#
# Options:
#   --dir DIR          install directory (default: ./sitebill)
#   --apps a.b,c.d     marketplace apps to install, comma separated (free apps need no account)
#   --preset ID        ready-made bundle of apps and trials: realestate | realtor-crm | booking | landing | content
#   --demo             load sample data into installed apps that have it (each app declares its own in manifest.demo)
#   --trial f1,f2|*    14-day trial of paid built-in apps (booking, crm_deals, ...), no account needed
#   --port N           web port (default: first free port from 3000)
#   --email EMAIL      admin email (default: admin@example.com)
#   --name NAME        site name (default: My Site)
#   --locale ru|en|sr|tg   default site language (default: en)
#   --version X.Y.Z    image version (default: latest)
#   --public           listen on all interfaces (default: 127.0.0.1 only)
#   --profile NAME     what kind of site to build: realestate (default: a real-estate agency site) or content (the built-in content factory: plan, calendar, team, AI), or blank (clean
#                      install for your OWN app: no real estate, the app brings the home page, menus and cabinet).
#                      Building a custom app for a client? use --profile blank
#   --no-update        do not install the newest platform release right after setup (default: update)
#   --no-telemetry     turn the anonymous daily statistics ping off. ONLY when the user explicitly asked for it:
#                      without the ping the installation is invisible to the platform owner (license server)
#   --source NAME      where you found us (llms, mcp, github, site) — anonymous statistics
#   --json             machine-readable output: exactly one JSON object on stdout
#   --timeout SEC      how long to wait for the stack (default: 900)

set -u

BASE_URL="${SITEBILL_BASE_URL:-https://sitebillcms.com}"
COMPOSE_URL="${SITEBILL_COMPOSE_URL:-$BASE_URL/install/docker-compose.yml}"
DIR="./sitebill"
APPS=""
TRIAL=""
DEMO=0
PRESET=""
UPDATE=1
TELEMETRY=true
PROFILE=""
PORT=""
EMAIL="admin@example.com"
NAME="My Site"
LOCALE="en"
VERSION=""
PUBLIC=0
SOURCE="direct"
JSON=0
TIMEOUT=900
STARTED=$(date +%s)

while [ $# -gt 0 ]; do
  case "$1" in
    --dir) DIR="$2"; shift 2 ;;
    --apps) APPS="$2"; shift 2 ;;
    --preset) PRESET="$2"; shift 2 ;;
    --trial) TRIAL="$2"; shift 2 ;;
    --demo) DEMO=1; shift ;;
    --no-update) UPDATE=0; shift ;;
    --no-telemetry) TELEMETRY=false; shift ;;
    --profile) PROFILE="$2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    --email) EMAIL="$2"; shift 2 ;;
    --name) NAME="$2"; shift 2 ;;
    --locale) LOCALE="$2"; shift 2 ;;
    --version) VERSION="$2"; shift 2 ;;
    --public) PUBLIC=1; shift ;;
    --source) SOURCE="$2"; shift 2 ;;
    --json) JSON=1; shift ;;
    --timeout) TIMEOUT="$2"; shift 2 ;;
    -h|--help) sed -n '2,27p' "$0" 2>/dev/null || echo "See $BASE_URL/install.md"; exit 0 ;;
    *) echo "Unknown option: $1 (see $BASE_URL/install.md)" >&2; exit 2 ;;
  esac
done

# ---------- output ----------

# JSON string escaping without jq: backslash, quotes, control characters, newlines.
json_str() {
  printf '%s' "$1" | awk 'BEGIN { ORS = ""; printf "\"" } {
    gsub(/\\/, "\\\\"); gsub(/"/, "\\\""); gsub(/\t/, "\\t"); gsub(/\r/, ""); gsub(/[\001-\010\013\014\016-\037]/, "");
    if (NR > 1) printf "\\n"; printf "%s", $0 } END { printf "\"" }'
}

say() { [ "$JSON" -eq 1 ] && echo "$*" >&2 || echo "$*"; }

# С --json скрипт обязан завершиться ровно одним JSON-объектом. Если он вышел иначе (сбой команды, обрыв), печатаем ошибку.
DONE=0
trap 'rc=$?; if [ "$DONE" -eq 0 ] && [ "$JSON" -eq 1 ]; then printf "{\"status\":\"error\",\"code\":\"aborted\",\"message\":\"The installer stopped before finishing (exit %s).\",\"hint\":\"Re-run the same command: it is safe and continues where it stopped.\",\"docs\":\"%s\"}
" "$rc" "$BASE_URL/install.md"; fi' EXIT

# fail CODE MESSAGE HINT — prints the error (JSON with --json) and exits.
fail() {
  DONE=1
  logs=""
  if [ -f "$DIR/docker-compose.yml" ] && command -v docker >/dev/null 2>&1; then
    logs=$(cd "$DIR" && docker compose logs --no-color --tail 40 api 2>/dev/null </dev/null | tail -n 40)
  fi
  if [ "$JSON" -eq 1 ]; then
    printf '{"status":"error","code":%s,"message":%s,"hint":%s,"docs":%s,"logs":%s}\n' \
      "$(json_str "$1")" "$(json_str "$2")" "$(json_str "$3")" "$(json_str "$BASE_URL/install.md")" "$(json_str "$logs")"
  else
    echo "ERROR [$1]: $2" >&2
    echo "Hint: $3" >&2
    [ -n "$logs" ] && { echo "--- last api logs ---" >&2; echo "$logs" >&2; }
  fi
  exit 1
}

rand_hex() {
  if command -v openssl >/dev/null 2>&1; then openssl rand -hex "$1"
  else head -c "$1" /dev/urandom | od -An -tx1 | tr -d ' \n'; fi
}

port_busy() {
  if command -v ss >/dev/null 2>&1; then ss -ltn 2>/dev/null | grep -q "[:.]$1 "
  elif command -v lsof >/dev/null 2>&1; then lsof -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1
  elif command -v nc >/dev/null 2>&1; then nc -z 127.0.0.1 "$1" >/dev/null 2>&1
  elif command -v netstat >/dev/null 2>&1; then netstat -an 2>/dev/null | grep -i listen | grep -q "[:.]$1 "  # Windows (Git Bash)
  else curl -s -o /dev/null --max-time 1 "http://127.0.0.1:$1" && return 0 || return 1
  fi
}

env_get() { [ -f "$DIR/.env" ] && sed -n "s/^$1=//p" "$DIR/.env" | tail -n 1; }

# ---------- preset ----------
# Пресет — именованный набор под задачу: приложения каталога и пробный период платных частей. Добавляется к тому, что
# передано в --apps / --trial. Состав пресетов описан в /install.md; расширять его можно без нового образа.

merge_list() { printf '%s,%s' "$1" "$2" | tr ',' '\n' | sed '/^$/d' | awk '!s[$0]++' | paste -sd, -; }

if [ -n "$PRESET" ]; then
  P_PROFILE=""
  case "$PRESET" in
    realestate)   P_APPS="sitebill.callback"; P_TRIAL="ai_search,export_feeds,new_buildings" ;;
    realtor-crm)  P_APPS="sitebill.callback"; P_TRIAL="crm_deals,telephony" ;;
    booking)      P_APPS="";                  P_TRIAL="booking" ;;
    landing)      P_APPS="sitebill.callback"; P_TRIAL="" ;;
    # Контент-фабрика приложением из каталога: чистая установка + приложение-владелец сайта (встроенный вариант — --profile content).
    content)      P_APPS="rumantic.content-manager"; P_TRIAL=""; P_PROFILE="blank" ;;
    *) fail bad_option "Unknown preset: $PRESET" "Use one of: realestate, realtor-crm, booking, landing, content (see $BASE_URL/install.md)." ;;
  esac
  [ -z "$PROFILE" ] && [ -n "$P_PROFILE" ] && PROFILE="$P_PROFILE"
  [ -n "$P_APPS" ] && APPS=$(merge_list "$APPS" "$P_APPS")
  [ -n "$P_TRIAL" ] && [ "$TRIAL" != "*" ] && TRIAL=$(merge_list "$TRIAL" "$P_TRIAL")
fi

# ---------- checks ----------

command -v curl >/dev/null 2>&1 || fail curl_missing "curl is not installed." "Install curl and run the installer again."
command -v docker >/dev/null 2>&1 || fail docker_missing "Docker is not installed." "Install Docker Engine (Linux) or Docker Desktop (macOS, Windows): https://docs.docker.com/get-docker/"
docker info >/dev/null 2>&1 || fail docker_not_running "Docker is installed but the daemon is not running or not accessible." "Start Docker (Docker Desktop, or: sudo systemctl start docker). On Linux the user may need to be in the docker group."
docker compose version >/dev/null 2>&1 || fail compose_missing "Docker Compose v2 (docker compose) is not available." "Install the Docker Compose plugin: https://docs.docker.com/compose/install/"
case "$LOCALE" in ru|en|sr|tg) ;; *) fail bad_option "Unsupported locale: $LOCALE" "Use one of: ru, en, sr, tg." ;; esac
case "$PROFILE" in ''|realestate|blank|content) ;; *) fail bad_option "Unknown profile: $PROFILE" "Use realestate (agency site), blank (clean install for your own app) or content (the built-in content factory)." ;; esac

mkdir -p "$DIR" || fail dir_failed "Cannot create directory $DIR." "Choose another --dir."
# Git Bash (Windows): curl.exe и docker не понимают /d/..., нужен путь вида D:/... (pwd -W). Агент часто выставляет
# MSYS_NO_PATHCONV=1 (для docker exec -w), и тогда /d/... не переписывается сам. В обычном sh `pwd -W` не поддерживается.
DIR=$(cd "$DIR" && { pwd -W 2>/dev/null || pwd; })

# ---------- files ----------

say "Downloading docker-compose.yml..."
curl -fsSL "$COMPOSE_URL" -o "$DIR/docker-compose.yml.new" || fail download_failed "Cannot download $COMPOSE_URL" "Check internet access; the file can also be taken from $BASE_URL/install.md."
mv "$DIR/docker-compose.yml.new" "$DIR/docker-compose.yml"

FRESH=0
INCOMPLETE=0
[ -f "$DIR/.install-incomplete" ] && INCOMPLETE=1
if [ ! -f "$DIR/.env" ]; then
  FRESH=1
  if [ -z "$PORT" ]; then
    PORT=3000
    while port_busy "$PORT"; do
      PORT=$((PORT + 1))
      [ "$PORT" -gt 3099 ] && fail port_busy "No free port between 3000 and 3099." "Pass --port N with a free port."
    done
  elif port_busy "$PORT"; then
    fail port_busy "Port $PORT is already in use." "Pass another --port or stop the program that uses it."
  fi
  BIND="127.0.0.1"; [ "$PUBLIC" -eq 1 ] && BIND="0.0.0.0"
  ADMIN_PASSWORD=$(rand_hex 9)
  # Своё имя проекта на каталог: в compose задано общее name, и две установки иначе делили бы один стек.
  PROJECT="sitebill-$(basename "$DIR" | tr 'A-Z' 'a-z' | tr -c 'a-z0-9\n' '-' | sed 's/^-*//; s/-*$//' | cut -c1-40)"
  umask 077
  cat > "$DIR/.env" <<EOF
# Generated by $BASE_URL/install.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ). Keep this file private.
COMPOSE_PROJECT_NAME=$PROJECT
APP_URL=http://localhost:$PORT
WEB_PORT=$PORT
WEB_BIND=$BIND
SANCTUM_STATEFUL_DOMAINS=localhost,localhost:$PORT,127.0.0.1:$PORT
DB_DATABASE=community
DB_USERNAME=community
DB_PASSWORD=$(rand_hex 16)
COMMUNITY_SITE_NAME=$NAME
COMMUNITY_DOMAIN=localhost
COMMUNITY_LOCALE=$LOCALE
COMMUNITY_ADMIN_EMAIL=$EMAIL
COMMUNITY_ADMIN_PASSWORD=$ADMIN_PASSWORD
COMMUNITY_INSTALL_SOURCE=$SOURCE
COMMUNITY_TELEMETRY=$TELEMETRY
COMMUNITY_PROFILE=${PROFILE:-realestate}
EOF
  [ -n "$VERSION" ] && echo "COMMUNITY_VERSION=$VERSION" >> "$DIR/.env"
  umask 022
  : > "$DIR/.install-incomplete"  # снимается в конце; пока он есть, повторный запуск ещё считает установку новой (профиль применится)
else
  say "Existing installation found in $DIR, keeping its .env."
  [ -n "$PROFILE" ] && [ "$INCOMPLETE" -eq 0 ] && say "Note: --profile is applied only to a NEW installation. Change the profile of this one in Admin > Apps, or: php artisan community:install --profile=$PROFILE"
  # Телеметрию не меняем молча ни в одну сторону, но предупреждаем: выключенная — установка не видна владельцу платформы.
  case "$(env_get COMMUNITY_TELEMETRY)" in
    false|0|no|off) say "Note: COMMUNITY_TELEMETRY=false in .env — this installation sends no statistics and will not appear in the platform owner's list. Turn it on only if the user wants that: set COMMUNITY_TELEMETRY=true and run 'docker compose up -d'." ;;
  esac
fi

URL=$(env_get APP_URL)
PORT=$(env_get WEB_PORT)
EMAIL=$(env_get COMMUNITY_ADMIN_EMAIL)
ADMIN_PASSWORD=$(env_get COMMUNITY_ADMIN_PASSWORD)

# ---------- start ----------

cd "$DIR" || fail dir_failed "Cannot enter $DIR." "Check permissions."
say "Pulling images (first run downloads about 1 GB)..."
docker compose pull -q >/dev/null 2>&1 </dev/null || fail pull_failed "Cannot pull Docker images." "Check internet access to Docker Hub (hub.docker.com) and free disk space."
say "Starting the stack (the first start runs database migrations, a few minutes)..."
# Не `up --wait`: он сдаётся, как только api стал unhealthy во время миграций (в старом compose короткий
# start_period). Повторяем `up -d`, пока api не станет healthy и web не запустится, или пока не выйдет время.
while :; do
  docker compose up -d >/dev/null 2>&1 </dev/null && break
  api_id=$(docker compose ps -a -q api 2>/dev/null)
  state=$([ -n "$api_id" ] && docker inspect -f '{{.State.Status}}' "$api_id" 2>/dev/null)
  [ "$state" = "exited" ] || [ "$state" = "dead" ] \
    && fail api_exited "The api container stopped during startup." "Read logs below or run 'docker compose logs api' in $DIR."
  [ $(( $(date +%s) - STARTED )) -ge "$TIMEOUT" ] \
    && fail health_timeout "The stack did not become healthy in ${TIMEOUT}s." "Check 'docker compose ps' and 'docker compose logs api' in $DIR; on a slow machine re-run with --timeout 1800."
  sleep 10
done

say "Waiting for the website..."
waited=0
restarted=0
until [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://127.0.0.1:$PORT/")" = "200" ]; do
  waited=$((waited + 5))
  # Docker Desktop иногда теряет проброс порта (контейнер отвечает внутри, снаружи connection refused): один перезапуск web лечит.
  if [ "$waited" -ge 90 ] && [ "$restarted" -eq 0 ]; then
    restarted=1; say "The website does not answer yet; restarting the web container once..."
    docker compose restart web >/dev/null 2>&1 </dev/null
  fi
  [ "$waited" -ge 300 ] && fail web_timeout "The website on port $PORT did not answer with 200." "Check 'docker compose ps' and 'docker compose logs web' in $DIR; if the container is Up but the port refuses connections, run 'docker compose restart web'. Port busy by another program? Re-run with --port N."
  sleep 5
done

# Каталог действующего релиза (самообновление переключает /data/releases/current), как в entrypoint.
# Git Bash (Windows) переписывает /data/... в C:/Program Files/Git/data/... — docker exec -w тогда падает; глобально
# отключать нельзя: curl и другие утилиты тогда не поймут пути вида /c/Users/....
# </dev/null обязателен: скрипт читается из stdin (`curl | sh`), и docker compose exec -T съедал остаток скрипта —
# установщик молча выходил с кодом 0 после проверки обновления, не поставив приложения.
artisan() { env MSYS_NO_PATHCONV=1 docker compose exec -T -w /data/releases/current/app/apps/api api php artisan "$@" </dev/null; }

# ---------- update ----------
# Образ мог выйти давно: сразу после установки подтягиваем свежий релиз платформы (самообновление, аккаунт не нужен),
# чтобы приложения и триал ставились на актуальную версию. Сбой не фатален: платформа уже работает.

jget() { printf '%s' "$2" | sed -n 's/.*"'"$1"'":"\([^"]*\)".*/\1/p'; }
upd_status() { artisan community:update --status --json 2>/dev/null | tail -n 1; }

UPDATE_JSON='{"status":"skipped"}'
if [ "$UPDATE" -eq 1 ]; then
  from=$(jget current_version "$(upd_status)")
  say "Checking for a newer platform release (installed: ${from:-unknown})..."
  out=$(artisan community:update --auto --force --json 2>/dev/null | tail -n 1)
  action=$(jget action "$out")
  case "$action" in
    updated|busy)
      # busy: то же обновление уже ведёт фоновый сервис контейнера. Ждём итог, потом, пока сайт снова ответит.
      waited=0
      while :; do
        st=$(jget state "$(upd_status)")
        case "$st" in done|idle|failed|rolled_back) break ;; esac
        waited=$((waited + 5)); [ "$waited" -ge 900 ] && break
        sleep 5
      done
      waited=0
      until [ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://127.0.0.1:$PORT/")" = "200" ]; do
        waited=$((waited + 5)); [ "$waited" -ge 300 ] && break
        sleep 5
      done
      to=$(jget current_version "$(upd_status)")
      if [ -n "$to" ] && [ "$to" != "$from" ]; then
        say "Platform updated: $from -> $to."
        UPDATE_JSON=$(printf '{"status":"updated","from":%s,"to":%s}' "$(json_str "$from")" "$(json_str "$to")")
      else
        UPDATE_JSON=$(printf '{"status":"unchanged","version":%s}' "$(json_str "$to")")
      fi ;;
    up_to_date) UPDATE_JSON=$(printf '{"status":"up_to_date","version":%s}' "$(json_str "$from")") ;;
    *) msg=$(jget message "$out")
       say "Platform update skipped: ${msg:-$action}. The installed version works; it retries automatically."
       UPDATE_JSON=$(printf '{"status":"failed","version":%s,"message":%s}' "$(json_str "$from")" "$(json_str "${msg:-$action}")") ;;
  esac
fi

# ---------- profile ----------
# COMMUNITY_PROFILE из .env применяет сам контейнер при первом старте, но образ с Docker Hub может быть старше
# профилей и его проигнорировать. После обновления платформы закрепляем явно выбранный профиль (blank и т.п.)
# самой командой: она идемпотентна и администратора не трогает.
if { [ "$FRESH" -eq 1 ] || [ "$INCOMPLETE" -eq 1 ]; } && [ -n "$PROFILE" ]; then
  say "Applying the site profile: $PROFILE"
  artisan community:install --skip-admin --profile="$PROFILE" >/dev/null 2>&1     || say "Note: could not apply the profile automatically. Run: php artisan community:install --skip-admin --profile=$PROFILE"
fi

# ---------- trial ----------

TRIAL_JSON="null"
if [ -n "$TRIAL" ]; then
  say "Starting the trial: $TRIAL"
  out=$(artisan community:trial "$TRIAL" --json 2>/dev/null | tail -n 1)
  case "$out" in
    '{"status":"ok"'*) TRIAL_JSON=$(printf '%s' "$out" | sed 's/^{"status":"ok",/{/') ;;
    *) msg=$(printf '%s' "$out" | sed -n 's/.*"message":"\([^"]*\)".*/\1/p')
       fail trial_failed "${msg:-Trial failed: $out}" "The platform itself is running at $URL (admin $EMAIL). A trial is given once per installation; paid apps can be bought at $BASE_URL/apps." ;;
  esac
fi

# ---------- apps ----------

APPS_JSON="[]"
if [ -n "$APPS" ]; then
  say "Installing apps: $APPS"
  out=$(artisan apps install "$APPS" --json 2>/dev/null | tail -n 1)
  case "$out" in
    '{"status":"ok"'*) APPS_JSON=$(printf '%s' "$out" | sed 's/^{"status":"ok","installed"://; s/}$//') ;;
    *) msg=$(printf '%s' "$out" | sed -n 's/.*"message":"\([^"]*\)".*/\1/p')
       fail apps_failed "${msg:-App installation failed: $out}" "The platform itself is running at $URL (admin $EMAIL). See $BASE_URL/apps for app ids; paid apps need a license key in Admin > Apps." ;;
  esac
fi

# ---------- demo data ----------
# Пример данных нужен, чтобы пользователь сразу увидел наполненный сайт. Команду сообщает само приложение
# (manifest.demo.command → `artisan apps demo <id>`); таблица ниже — только для уже выпущенных версий без этого поля.
# Ошибка демо установку не валит.

DEMO_JSON="[]"
DEMO_AVAILABLE=""
if [ -n "$APPS" ]; then
  for app in $(printf '%s' "$APPS" | tr ',' ' '); do
    app="${app%%@*}"
    chk=$(artisan apps demo "$app" --check --json 2>/dev/null | tail -n 1)
    case "$chk" in
      '{"status":"ok"'*) has=1 ;;
      *) has=0
         case "$app" in rumantic.content-manager) has=2 ;; esac ;;
    esac
    [ "$has" -eq 0 ] && continue
    DEMO_AVAILABLE="$DEMO_AVAILABLE $app"
    [ "$DEMO" -eq 0 ] && continue
    say "Loading sample data: $app"
    if [ "$has" -eq 1 ]; then out=$(artisan apps demo "$app" --json 2>/dev/null | tail -n 1); else out=$(artisan cm:seed-demo --json 2>/dev/null | tail -n 1); fi
    case "$out" in
      '{"status":"ok"'*|'{"status":"skipped"'*) DEMO_JSON=$(printf '%s' "$DEMO_JSON" | sed 's/\]$//; s/^\[$/[/'); [ "$DEMO_JSON" = "[" ] && DEMO_JSON="[$out]" || DEMO_JSON="$DEMO_JSON,$out]" ;;
      *) say "Note: sample data for $app was not loaded. Run: php artisan apps demo $app" ;;
    esac
  done
fi

NEXT_DEMO=""
[ "$DEMO" -eq 0 ] && [ -n "$DEMO_AVAILABLE" ] && NEXT_DEMO=" The site is empty: for a filled-in example rerun the same command with --demo (sample data for:$DEMO_AVAILABLE)."

TOOK=$(( $(date +%s) - STARTED ))
rm -f "$DIR/.install-incomplete"
DONE=1

if [ "$JSON" -eq 1 ]; then
  printf '{"status":"ok","url":%s,"admin_url":%s,"admin":{"email":%s,"password":%s},"apps":%s,"profile":%s,"preset":%s,"demo":%s,"trial":%s,"update":%s,"dir":%s,"fresh":%s,"took_s":%s,"next":%s}\n' \
    "$(json_str "$URL")" "$(json_str "$URL/admin")" "$(json_str "$EMAIL")" "$(json_str "$ADMIN_PASSWORD")" "$APPS_JSON" "$(P=$(env_get COMMUNITY_PROFILE); [ -n "$P" ] && json_str "$P" || echo null)" "$([ -n "$PRESET" ] && json_str "$PRESET" || echo null)" "$DEMO_JSON" "$TRIAL_JSON" "$UPDATE_JSON" \
    "$(json_str "$DIR")" "$([ "$FRESH" -eq 1 ] && echo true || echo false)" "$TOOK" \
    "$(json_str "Open admin_url and sign in.$NEXT_DEMO Manage apps: cd $DIR && docker compose exec -T -w /data/releases/current/app/apps/api api php artisan apps list --json")"
else
  echo ""
  echo "Sitebill is running ($TOOK s)."
  echo "  Website: $URL"
  echo "  Admin:   $URL/admin"
  echo "  Login:   $EMAIL"
  echo "  Password: $ADMIN_PASSWORD"
  echo "  Files:   $DIR (credentials are in .env)"
  [ -n "$APPS" ] && echo "  Apps:    $APPS"
  [ -n "$TRIAL" ] && echo "  Trial:   $TRIAL"
  [ -n "$PRESET" ] && echo "  Preset:  $PRESET"
  [ -n "$(env_get COMMUNITY_PROFILE)" ] && echo "  Profile: $(env_get COMMUNITY_PROFILE)"
fi
