#!/bin/bash
# =============================================================================
# officer-setup — the install layout
# =============================================================================
#
# Definitions only.
#
# ── One root, and nothing configurable underneath it ──
#
#   $OFFICER_ROOT/
#     platform/      the app — the git checkout
#     data/          DATA_PATH: managed homes, attachments, job logs
#     dockers/       services the app store provisioned
#     capabilities/  the file-based item store — skills, tools, tasks, processes
#
# The original asked separately for DATA_PATH and for OFFICER_ITEMS_DIR, and left
# the app store's directory implicit. Three answers that had to agree with each
# other, given by somebody with no reason to know they had to.
#
# Now one question — where the root goes — and the rest follows. Anybody who wants
# data/ on a bigger volume can symlink it; that is a decision about storage, not
# about how Officer is laid out, and it does not need a prompt in a setup script.
#
# This is also what the code already assumes. app-store/paths.ts derives
# OFFICER_ROOT as dirname(DATA_PATH) and DOCKERS_DIR as OFFICER_ROOT/dockers, so
# setting DATA_PATH to <root>/data is the whole of what makes the layout correct.

[[ -n "${OFFICER_SETUP_LAYOUT_LOADED:-}" ]] && return 0
OFFICER_SETUP_LAYOUT_LOADED=1

layout_data_dir() { echo "${OFFICER_ROOT}/data"; }
layout_dockers_dir() { echo "${OFFICER_ROOT}/dockers"; }
layout_items_dir() { echo "${OFFICER_ROOT}/capabilities"; }

layout_dirs() {
  echo "$OFFICER_ROOT"
  echo "$(layout_data_dir)"
  echo "$(layout_dockers_dir)"
  echo "$(layout_items_dir)"
}

# Created owned by the account, because everything that writes into them runs as
# the account: the platform under pm2, the app store's compose files, the item
# store the agent authors into.
create_layout() {
  local dir
  while read -r dir; do
    [[ -d "$dir" ]] || install -d -m 0755 -o "$USERNAME" -g "$(user_group)" "$dir"
  done < <(layout_dirs)
  return 0
}

# A directory that exists but belongs to somebody else is the failure this
# reports: it happens when an earlier run, or a hand-made directory, was created
# as root, and everything written into it afterwards fails in a way that reads as
# a permissions bug in the platform.
layout_wrong_owner() {
  local dir
  while read -r dir; do
    [[ -d "$dir" ]] || continue
    [[ "$(stat -c %U "$dir")" == "$USERNAME" ]] || echo "$dir"
  done < <(layout_dirs)
}
