#include "assets.h"
#include "platform.h"
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
constexpr size_t PATH_CAP = 4096;
static char asset_text[ASSET_TEXT_MAX];
static size_t asset_used;
typedef struct {
NameList *list;
AssetKind kind;
const char *dir;
uint8_t ward;
} Listing;
static int add_asset(void *state, const char *entry)
{
Listing *l = state;
if (entry[0] == '.') return 0;
char path[PATH_CAP];
[[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", l->dir, entry);
ensure(n > 0 && (size_t)n < sizeof path); // PATH_ROOM leaves room for an entry's name
struct stat st = {};
(void)sys_stat(path, &st);
bool wanted = l->kind == AK_SKILL ? S_ISDIR(st.st_mode) : S_ISREG(st.st_mode);
if (!wanted) return 0;
size_t len = strlen(entry);
bool md = l->kind != AK_SKILL && len > 3 && strcmp(entry + len - 3, ".md") == 0;
size_t name_len = md ? len - 3 : len;
if (l->list->n == ASSET_MAX || asset_used + len + 1 + name_len + 1 > ASSET_TEXT_MAX) {
say(STDERR_FILENO, "suit: the store has too many %s (limit %u, %zu bytes of names)\n",
asset_kind_name(l->kind), ASSET_MAX, ASSET_TEXT_MAX);
return 1;
}
char *file = asset_text + asset_used;
memcpy(file, entry, len + 1);
char *name = file + len + 1;
memcpy(name, entry, name_len);
name[name_len] = '\0';
asset_used += len + 1 + name_len + 1;
l->list->file[l->list->n] = file;
l->list->ward[l->list->n] = l->ward;
l->list->name[l->list->n++] = name;
return 0;
}
// Names in order, so the plan does not depend on the order the folder lists.
// Equal names stay in the order of their wardrobes.
static void sort_names(NameList *l)
{
for (uint32_t i = 1; i < l->n; i++) {
for (uint32_t j = i; j > 0 && strcmp(l->name[j - 1], l->name[j]) > 0; j--) {
const char *name = l->name[j];
const char *file = l->file[j];
uint8_t ward = l->ward[j];
l->name[j] = l->name[j - 1];
l->file[j] = l->file[j - 1];
l->ward[j] = l->ward[j - 1];
l->name[j - 1] = name;
l->file[j - 1] = file;
l->ward[j - 1] = ward;
}
}
}
// What every wardrobe's store holds, each asset marked with its wardrobe.
int assets_load(const Wards *w, Assets *a)
{
static const char *const dirs[AK_COMMAND + 1] = {"skills", "agents", "commands"};
asset_used = 0;
for (int k = AK_SKILL; k <= AK_COMMAND; k++) a->list[k].n = 0;
for (uint32_t wi = 0; wi < w->n; wi++) {
for (int k = AK_SKILL; k <= AK_COMMAND; k++) {
char dir[PATH_CAP];
[[maybe_unused]] int n = snprintf(dir, sizeof dir, "%s/%s", w->w[wi].store, dirs[k]);
ensure(n > 0 && (size_t)n < sizeof dir);
Listing l = {&a->list[k], (AssetKind)k, dir, (uint8_t)wi};
int rc = sys_listdir(dir, add_asset, &l);
if (rc > 0) return 1;
if (rc < 0 && errno != ENOENT) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", dir, strerror(errno));
return 1;
}
}
}
for (int k = AK_SKILL; k <= AK_COMMAND; k++) sort_names(&a->list[k]);
return 0;
}