#include "server.h"

#include "auth.h"
#include "crypto.h"
#include "net.h"
#include "protocol.h"
#include "store.h"
#include "wire.h"

#include <blake3.h>

#include <algorithm>
#include <cstddef>
#include <cstring>
#include <iostream>
#include <optional>
#include <set>
#include <string>

namespace vn::server {

namespace {

constexpr std::size_t MAX_CHUNKS_PER_REQUEST = 4096;

struct Session {
  net::Stream stream;
  fs::path repo_root;
  bool repo_present = false;
  Store store;
  bool store_open = false;
  auth::Access access;
  std::string hello_repo;
  std::string server_nonce;
  std::string client_nonce;
  std::string binding;
  std::uint16_t version = proto::PROTOCOL_VERSION;
  bool authed = false;
  std::uint8_t role = auth::ROLE_ANONYMOUS;
  PublicKey public_key{};
  bool has_public_key = false;
  std::string fingerprint;
  std::vector<Id> haves;
  int failed_auth = 0;
  bool closing = false;
  fs::path root;
};

std::uint8_t effective_role(const Session &session) {
  if (session.authed)
    return session.role;
  if (session.access.valid && session.access.anonymous_read &&
      session.repo_present)
    return auth::ROLE_READ;
  return auth::ROLE_ANONYMOUS;
}

bool deny(Session &session, std::uint32_t request_id, bool write) {
  const std::uint8_t role = effective_role(session);
  if (write) {
    if (role == auth::ROLE_WRITE)
      return false;
    if (!session.authed) {
      wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,
                        "authentication required");
    } else {
      wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,
                        "write role required");
    }
    return true;
  }
  if (role == auth::ROLE_READ || role == auth::ROLE_WRITE)
    return false;
  if (!session.authed) {
    wire::write_error(session.stream, request_id, wire::ERR_UNAUTHENTICATED,
                      "authentication required");
  } else {
    wire::write_error(session.stream, request_id, wire::ERR_FORBIDDEN,
                      "read role required");
  }
  return true;
}

void log_line(Session &session, std::string_view text) {
  if (!session.repo_present)
    return;
  (void)append_file(veins_dir(session.repo_root) / "server.log",
                    bytes_of(text));
}

void log_outcome(Session &session, std::string_view outcome) {
  if (!session.repo_present)
    return;
  const std::string line =
      std::to_string(unix_now_millis()) + " " +
      std::string(proto::role_name(effective_role(session))) + " " +
      std::string(outcome) + " " + session.hello_repo + "\n";
  log_line(session, line);
}

bool safe_repo_name(std::string_view name) {
  if (name.empty() || name.size() > 4096)
    return false;
  if (name.front() == '/')
    return false;
  if (name.find('\0') != std::string_view::npos ||
      name.find('\\') != std::string_view::npos)
    return false;
  std::size_t start = 0;
  for (std::size_t i = 0; i <= name.size(); ++i) {
    if (i == name.size() || name[i] == '/') {
      if (i - start == 2 && name[start] == '.' && name[start + 1] == '.')
        return false;
      start = i + 1;
    }
  }
  return true;
}

void open_session_store(Session &session) {
  if (session.store_open)
    return;
  session.store = Store::open_all(session.repo_root);
  session.store_open = true;
}

void select_repo(Session &session, bool has_root) {
  if (session.repo_present || !has_root)
    return;
  if (!safe_repo_name(session.hello_repo))
    return;
  const fs::path joined = session.root / path_from_bytes(session.hello_repo);
  if (auto found = discover_repo(joined)) {
    session.repo_root = *found;
    session.repo_present = true;
  }
}

std::string change_id_of(Session &session, const Id &id) {
  auto loaded = load_commit(session.store, id);
  if (!loaded)
    return {};
  return std::string(reinterpret_cast<const char *>(loaded->commit.change_id.data()),
                     loaded->commit.change_id.size());
}

bool send_record(Session &session, std::uint32_t request_id,
                 blake3_hasher &hasher, const Id &id, std::uint8_t kind,
                 Bytes body) {
  const auto record = wire::make_record(id, kind, body);
  blake3_hasher_update(&hasher, record.data(), record.size());
  return wire::write_frame(session.stream, wire::RECORDS, request_id,
                           Bytes(record.data(), record.size()));
}

bool send_end(Session &session, std::uint32_t request_id,
              blake3_hasher &hasher) {
  std::array<std::uint8_t, 32> digest{};
  blake3_hasher_finalize(&hasher, digest.data(), digest.size());
  return wire::write_frame(session.stream, wire::END, request_id,
                           Bytes(digest.data(), digest.size()));
}

std::uint8_t value_kind_to_type(std::uint8_t kind) {
  if (kind == KIND_SUBTREE)
    return TYPE_TREE;
  if (kind == KIND_CONFLICT)
    return TYPE_CONFLICT;
  if (kind == KIND_FILE || kind == KIND_EXECUTABLE || kind == KIND_SYMLINK)
    return TYPE_BLOB;
  return 0;
}

void collect_object(Session &session, std::uint32_t request_id,
                    blake3_hasher &hasher, const Id &id, std::uint8_t kind,
                    std::set<Id> &seen, bool send, bool &failed);

void collect_tree(Session &session, std::uint32_t request_id,
                  blake3_hasher &hasher, const Id &id, std::set<Id> &seen,
                  bool send, bool &failed) {
  if (!seen.insert(id).second)
    return;
  auto body = session.store.read_body(id, TYPE_TREE);
  if (!body) {
    failed = true;
    return;
  }
  if (send && !send_record(session, request_id, hasher, id, TYPE_TREE,
                           bytes_of(*body))) {
    failed = true;
  }
  auto tree = decode_tree(bytes_of(*body));
  if (!tree) {
    failed = true;
    return;
  }
  for (const auto &entry : tree->entries) {
    if (entry.kind == KIND_SUBTREE) {
      collect_tree(session, request_id, hasher, entry.target, seen, send,
                   failed);
    } else if (entry.kind == KIND_CONFLICT) {
      collect_object(session, request_id, hasher, entry.target, TYPE_CONFLICT,
                     seen, send, failed);
    } else if (entry.kind != KIND_SUBMODULE) {
      collect_object(session, request_id, hasher, entry.target, TYPE_BLOB, seen,
                     send, failed);
    }
    if (failed)
      return;
  }
}

void collect_object(Session &session, std::uint32_t request_id,
                    blake3_hasher &hasher, const Id &id, std::uint8_t kind,
                    std::set<Id> &seen, bool send, bool &failed) {
  if (!seen.insert(id).second)
    return;
  auto body = session.store.read_body(id, kind);
  if (!body) {
    failed = true;
    return;
  }
  if (send && !send_record(session, request_id, hasher, id, kind,
                           bytes_of(*body))) {
    failed = true;
  }
  if (kind == TYPE_BLOB) {
    auto blob = decode_blob(bytes_of(*body));
    if (!blob) {
      failed = true;
      return;
    }
    if (blob->form == BlobForm::Interior) {
      for (const auto &entry : blob->entries) {
        collect_object(session, request_id, hasher, entry.id, TYPE_BLOB, seen,
                       send, failed);
        if (failed)
          return;
      }
    }
  } else if (kind == TYPE_CONFLICT) {
    auto conflict = decode_conflict(bytes_of(*body));
    if (!conflict) {
      failed = true;
      return;
    }
    for (const auto &value : conflict->adds) {
      if (!value.target)
        continue;
      const std::uint8_t child = value_kind_to_type(value.kind);
      if (child != 0)
        collect_object(session, request_id, hasher, *value.target, child, seen,
                       send, failed);
      if (failed)
        return;
    }
    for (const auto &value : conflict->removes) {
      if (!value.target)
        continue;
      const std::uint8_t child = value_kind_to_type(value.kind);
      if (child != 0)
        collect_object(session, request_id, hasher, *value.target, child, seen,
                       send, failed);
      if (failed)
        return;
    }
  }
}

bool handle_hello(Session &session, const wire::Frame &frame, bool has_root) {
  auto hello = proto::decode_hello(bytes_of(frame.payload));
  if (!hello) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "bad HELLO");
    return false;
  }
  if (hello->min_version > proto::PROTOCOL_VERSION ||
      hello->max_version < proto::PROTOCOL_VERSION) {
    wire::write_error(session.stream, frame.request_id,
                      wire::ERR_UNSUPPORTED_VERSION, "no common version");
    return false;
  }
  session.version = proto::PROTOCOL_VERSION;
  session.hello_repo = std::move(hello->repo);
  session.client_nonce = std::move(hello->client_nonce);
  select_repo(session, has_root);
  if (!session.repo_present && !session.hello_repo.empty()) {
    error_prefix();
    std::cout << "repository not found: " << session.hello_repo << "\n";
    wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,
                      "repository not found");
    return false;
  }
  if (session.repo_present) {
    session.access = auth::load_access(session.repo_root);
    if (!session.access.valid) {
      error_prefix();
      std::cout << "access file error at line " << session.access.error_line
                << " in " << path_display(session.repo_root) << "\n";
      wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,
                        "invalid access file");
      return false;
    }
    open_session_store(session);
  }
  log_outcome(session, "hello");

  const auto nonce = secure_random(32);
  if (nonce.size() != 32) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,
                      "cannot generate nonce");
    return false;
  }
  session.server_nonce.assign(reinterpret_cast<const char *>(nonce.data()),
                              nonce.size());

  proto::HelloOk hello_ok;
  hello_ok.version = session.version;
  hello_ok.capabilities = {"zstd-records", "lazy-chunks", "push",
                           "auth-ed25519"};
  hello_ok.server_nonce = session.server_nonce;
  hello_ok.auth_required =
      (session.repo_present && session.access.anonymous_read) ? 0 : 1;
  const auto body = proto::encode_hello_ok(hello_ok);
  return wire::write_frame(session.stream, wire::HELLO_OK, frame.request_id,
                           body);
}

bool handle_auth(Session &session, const wire::Frame &frame) {
  if (session.authed) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "repeated AUTH");
    session.closing = true;
    return false;
  }
  auto auth = proto::decode_auth(bytes_of(frame.payload));
  if (!auth) {
    ++session.failed_auth;
    wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,
                      "authentication failed");
    if (session.failed_auth >= 3)
      session.closing = true;
    return true;
  }
  PublicKey public_key{};
  const bool key_well_formed = auth->public_key.size() == public_key.size();
  if (key_well_formed) {
    std::memcpy(public_key.data(), auth->public_key.data(),
                public_key.size());
  }
  std::uint8_t role = auth::ROLE_UNKNOWN;
  if (key_well_formed && session.repo_present && session.access.valid)
    role = auth::role_for(session.access, &public_key);

  const std::string message = proto::auth_message(
      session.version, session.hello_repo, bytes_of(session.server_nonce),
      bytes_of(session.client_nonce), bytes_of(session.binding));
  const bool signature_ok =
      role != auth::ROLE_UNKNOWN &&
      ed25519_verify(public_key, bytes_of(message), bytes_of(auth->signature));
  if (!signature_ok) {
    ++session.failed_auth;
    wire::write_error(session.stream, frame.request_id, wire::ERR_AUTH_FAILED,
                      "authentication failed");
    if (session.failed_auth >= 3)
      session.closing = true;
    return true;
  }

  session.authed = true;
  session.role = role;
  session.public_key = public_key;
  session.has_public_key = true;
  const auto raw_fingerprint = key_fingerprint_bytes(public_key);
  session.fingerprint.assign(
      reinterpret_cast<const char *>(raw_fingerprint.data()),
      raw_fingerprint.size());

  proto::AuthOk auth_ok;
  auth_ok.role = role;
  auth_ok.fingerprint = session.fingerprint;
  const auto body = proto::encode_auth_ok(auth_ok);
  const bool wrote = wire::write_frame(session.stream, wire::AUTH_OK,
                                       frame.request_id, body);
  log_outcome(session, "auth-ok");
  return wrote;
}

bool handle_whoami(Session &session, const wire::Frame &frame) {
  ByteWriter writer(64);
  writer.u8(effective_role(session));
  writer.length_prefixed(session.fingerprint);
  return wire::write_frame(session.stream, wire::WHOAMI_OK, frame.request_id,
                           writer.view());
}

bool handle_list_refs(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, false))
    return true;
  log_outcome(session, "list-refs");
  std::optional<View> view = current_view(session.repo_root, session.store);
  if (!view) {
    const auto heads = read_heads(session.repo_root);
    if (!heads.empty()) {
      wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,
                        "cannot read operation state");
      log_outcome(session, "list-refs-error");
      return true;
    }
    view = empty_view();
  }
  std::vector<proto::RefInfo> refs;
  for (const auto &bookmark : view->bookmarks) {
    if (bookmark.targets.adds.size() != 1 || !bookmark.targets.adds.front())
      continue;
    proto::RefInfo ref;
    ref.name = bookmark.name;
    ref.target = *bookmark.targets.adds.front();
    ref.change_id = change_id_of(session, ref.target);
    ref.kind = 0;
    refs.push_back(std::move(ref));
  }
  for (const auto &tag : view->tags) {
    proto::RefInfo ref;
    ref.name = tag.name;
    ref.target = tag.target;
    ref.change_id = change_id_of(session, tag.target);
    ref.kind = 1;
    refs.push_back(std::move(ref));
  }
  const auto body = proto::encode_refs(refs);
  const bool wrote =
      wire::write_frame(session.stream, wire::REFS, frame.request_id, body);
  if (!wrote)
    log_outcome(session, "list-refs-write-error");
  return wrote;
}

bool handle_negotiate(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, false))
    return true;
  auto negotiate = proto::decode_negotiate(bytes_of(frame.payload));
  if (!negotiate) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "bad NEGOTIATE");
    return true;
  }
  session.haves = std::move(negotiate->haves);
  std::vector<std::uint8_t> known;
  known.reserve(session.haves.size());
  bool any_known = false;
  for (const auto &id : session.haves) {
    const bool found = session.store.find(id).has_value();
    known.push_back(found ? 1 : 0);
    any_known = any_known || found;
  }
  const std::uint8_t enough =
      (session.haves.empty() || any_known) ? 1 : 0;
  const auto body = proto::encode_negotiate_ok(known, enough);
  return wire::write_frame(session.stream, wire::NEGOTIATE_OK,
                           frame.request_id, body);
}

bool handle_fetch(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, false))
    return true;
  auto wants = proto::decode_ids(bytes_of(frame.payload), 1000000);
  if (!wants) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "bad wants");
    return true;
  }
  if (wants->empty()) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "empty wants");
    return true;
  }
  const auto all = collect_commits(session.store, *wants);
  std::set<Id> exclude;
  for (const auto &have : session.haves) {
    const std::array<Id, 1> roots{have};
    for (const auto &id : collect_commits(session.store, roots))
      exclude.insert(id);
  }

  blake3_hasher hasher;
  blake3_hasher_init(&hasher);
  bool failed = false;
  std::set<Id> seen;
  for (const auto &id : all) {
    if (exclude.contains(id))
      continue;
    auto loaded = load_commit(session.store, id);
    if (!loaded) {
      failed = true;
      break;
    }
    if (!send_record(session, frame.request_id, hasher, id, TYPE_COMMIT,
                     bytes_of(loaded->body))) {
      failed = true;
      break;
    }
    collect_tree(session, frame.request_id, hasher, loaded->commit.root_tree,
                 seen, true, failed);
    if (failed)
      break;
  }
  if (!failed)
    (void)send_end(session, frame.request_id, hasher);
  log_outcome(session, "fetch");
  return !failed;
}

bool handle_get_chunks(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, false))
    return true;
  auto ids = proto::decode_ids(bytes_of(frame.payload),
                               MAX_CHUNKS_PER_REQUEST);
  if (!ids) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "bad chunk list");
    return true;
  }
  blake3_hasher hasher;
  blake3_hasher_init(&hasher);
  bool failed = false;
  for (const auto &id : *ids) {
    const auto loc = session.store.find(id);
    if (!loc || loc->kind != TYPE_CHUNK) {
      failed = true;
      break;
    }
    auto body = session.store.get(*loc);
    if (!body) {
      failed = true;
      break;
    }
    if (!send_record(session, frame.request_id, hasher, id, TYPE_CHUNK,
                     bytes_of(*body))) {
      failed = true;
      break;
    }
  }
  if (failed) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_NOT_FOUND,
                      "chunk not found");
  } else {
    (void)send_end(session, frame.request_id, hasher);
  }
  return !failed;
}

bool handle_have_query(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, true))
    return true;
  auto ids = proto::decode_ids(bytes_of(frame.payload), 1000000);
  if (!ids) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "bad HAVE_QUERY");
    return true;
  }
  std::vector<std::uint8_t> bits;
  bits.reserve(ids->size());
  for (const auto &id : *ids)
    bits.push_back(session.store.find(id).has_value() ? 1 : 0);
  const auto body = proto::encode_bitmap(bits);
  return wire::write_frame(session.stream, wire::HAVE_BITMAP,
                           frame.request_id, body);
}

bool object_exists(Session &session, const Id &id) {
  return session.store.find(id).has_value();
}

bool check_closure(Session &session, const Id &id, std::uint8_t kind) {
  auto body = session.store.read_body(id, kind);
  if (!body)
    return false;
  bool fine = true;
  if (kind == TYPE_COMMIT) {
    auto commit = decode_commit(bytes_of(*body));
    if (!commit)
      return false;
    if (!object_exists(session, commit->root_tree))
      fine = false;
    for (const auto &parent : commit->parents) {
      if (!object_exists(session, parent))
        fine = false;
    }
  } else if (kind == TYPE_TREE) {
    auto tree = decode_tree(bytes_of(*body));
    if (!tree)
      return false;
    for (const auto &entry : tree->entries) {
      if (entry.kind != KIND_SUBMODULE && !object_exists(session, entry.target))
        fine = false;
    }
  } else if (kind == TYPE_BLOB) {
    auto blob = decode_blob(bytes_of(*body));
    if (!blob)
      return false;
    for (const auto &entry : blob->entries) {
      if (!object_exists(session, entry.id))
        fine = false;
    }
  } else if (kind == TYPE_CONFLICT) {
    auto conflict = decode_conflict(bytes_of(*body));
    if (!conflict)
      return false;
    for (const auto &value : conflict->adds) {
      if (value.target && !object_exists(session, *value.target))
        fine = false;
    }
    for (const auto &value : conflict->removes) {
      if (value.target && !object_exists(session, *value.target))
        fine = false;
    }
  }
  return fine;
}

bool handle_put_records(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, true))
    return true;
  Writer writer;
  blake3_hasher hasher;
  blake3_hasher_init(&hasher);
  bool failed = false;
  std::vector<Id> accepted;

  for (;;) {
    auto frame_opt = wire::read_frame(session.stream);
    if (!frame_opt) {
      failed = true;
      break;
    }
    const auto &incoming = *frame_opt;
    if (incoming.kind == wire::END) {
      std::array<std::uint8_t, 32> digest{};
      blake3_hasher_finalize(&hasher, digest.data(), digest.size());
      if (incoming.payload.size() != digest.size() ||
          std::memcmp(incoming.payload.data(), digest.data(), digest.size()) !=
              0) {
        failed = true;
      }
      break;
    }
    if (incoming.kind != wire::RECORDS) {
      failed = true;
      break;
    }
    blake3_hasher_update(&hasher, incoming.payload.data(),
                         incoming.payload.size());
    auto record = wire::parse_record(bytes_of(incoming.payload));
    if (!record) {
      failed = true;
      break;
    }
    const Id computed = object_id(record->kind, bytes_of(record->body));
    if (std::memcmp(computed.data(), record->id.data(), ID_LEN) != 0) {
      failed = true;
      break;
    }
    writer.add_known(record->kind, record->id, std::move(record->body));
    accepted.push_back(record->id);
  }

  if (failed) {
    wire::write_error(session.stream, frame.request_id,
                      wire::ERR_HASH_MISMATCH, "record rejected");
    return true;
  }
  if (!writer.finish(session.repo_root)) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,
                      "pack write failed");
    return true;
  }
  open_session_store(session);
  session.store.refresh(session.repo_root);

  bool closure_ok = true;
  for (const auto &id : accepted) {
    const auto loc = session.store.find(id);
    if (!loc)
      continue;
    if (!check_closure(session, id, loc->kind)) {
      closure_ok = false;
      break;
    }
  }
  if (!closure_ok) {
    wire::write_error(session.stream, frame.request_id,
                      wire::ERR_MISSING_CLOSURE, "missing object closure");
    return true;
  }
  return wire::write_frame(session.stream, wire::END, frame.request_id,
                           Bytes{});
}

std::optional<Id> first_target(const TargetSet &targets) {
  if (targets.adds.empty())
    return std::nullopt;
  return targets.adds.front();
}

bool ref_matches(const View &view, std::string_view name,
                 const std::optional<Id> &expected) {
  std::optional<Id> current;
  if (auto index = find_bookmark(view, name)) {
    current = first_target(view.bookmarks[*index].targets);
  } else if (auto index = find_tag(view, name)) {
    current = view.tags[*index].target;
  }
  if (!expected)
    return !current.has_value();
  if (!current)
    return false;
  return std::memcmp(current->data(), expected->data(), ID_LEN) == 0;
}

void apply_ref(View &view, std::string_view name,
               const std::optional<Id> &target) {
  if (!target) {
    if (auto index = find_bookmark(view, name))
      view.bookmarks.erase(view.bookmarks.begin() +
                           static_cast<std::ptrdiff_t>(*index));
    if (auto index = find_tag(view, name))
      view.tags.erase(view.tags.begin() +
                      static_cast<std::ptrdiff_t>(*index));
    return;
  }
  if (auto index = find_bookmark(view, name)) {
    auto &bookmark = view.bookmarks[*index];
    bookmark.targets.adds = {*target};
    bookmark.targets.removes.clear();
    return;
  }
  if (auto index = find_tag(view, name)) {
    view.tags[*index].target = *target;
    return;
  }
  Bookmark bookmark;
  bookmark.name = std::string(name);
  bookmark.targets.adds = {*target};
  view.bookmarks.push_back(std::move(bookmark));
}

bool handle_update_refs(Session &session, const wire::Frame &frame) {
  if (deny(session, frame.request_id, true))
    return true;
  auto updates = proto::decode_update_refs(bytes_of(frame.payload));
  if (!updates) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                      "bad UPDATE_REFS");
    return true;
  }
  auto tx = Txn::begin(session.repo_root, session.store);
  if (!tx) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,
                      "cannot update refs");
    return true;
  }
  for (const auto &update : *updates) {
    if (!ref_matches(tx->view(), update.name, update.expected)) {
      wire::write_error(session.stream, frame.request_id,
                        wire::ERR_REF_CONFLICT, "ref changed");
      return true;
    }
  }
  for (const auto &update : *updates)
    apply_ref(tx->view(), update.name, update.target);
  rebuild_heads(tx->view());
  const auto status = tx->finish("remote push");
  if (!status) {
    wire::write_error(session.stream, frame.request_id, wire::ERR_INTERNAL,
                      "commit failed");
    return true;
  }
  session.store.refresh(session.repo_root);
  const std::string line = std::to_string(unix_now_millis()) + " " +
                           base32_text(bytes_of(session.fingerprint)) +
                           " update-refs\n";
  log_line(session, line);
  return wire::write_simple(session.stream, wire::UPDATE_REFS_OK,
                            frame.request_id);
}

bool dispatch(Session &session, const wire::Frame &frame) {
  if (frame.kind == wire::HELLO)
    return handle_hello(session, frame, !session.root.empty());
  if (frame.kind == wire::AUTH)
    return handle_auth(session, frame);
  if (frame.kind == wire::WHOAMI)
    return handle_whoami(session, frame);
  if (!session.repo_present) {
    wire::write_error(session.stream, frame.request_id,
                      wire::ERR_UNAUTHENTICATED, "authentication required");
    return true;
  }
  if (frame.kind == wire::LIST_REFS)
    return handle_list_refs(session, frame);
  if (frame.kind == wire::NEGOTIATE)
    return handle_negotiate(session, frame);
  if (frame.kind == wire::FETCH_SKELETON)
    return handle_fetch(session, frame);
  if (frame.kind == wire::GET_CHUNKS)
    return handle_get_chunks(session, frame);
  if (frame.kind == wire::HAVE_QUERY)
    return handle_have_query(session, frame);
  if (frame.kind == wire::PUT_RECORDS)
    return handle_put_records(session, frame);
  if (frame.kind == wire::UPDATE_REFS)
    return handle_update_refs(session, frame);
  wire::write_error(session.stream, frame.request_id, wire::ERR_BAD_FRAME,
                    "unknown request");
  return true;
}

void run_session(net::Stream stream, std::optional<fs::path> fixed,
                 std::optional<fs::path> root, std::string binding) {
  Session session;
  session.stream = std::move(stream);
  session.binding = std::move(binding);
  if (root)
    session.root = *root;
  if (fixed) {
    session.repo_root = *fixed;
    session.repo_present = true;
    session.access = auth::load_access(session.repo_root);
    if (session.access.valid)
      open_session_store(session);
  }
  while (!session.closing) {
    auto frame = wire::read_frame(session.stream);
    if (!frame)
      break;
    const bool keep = dispatch(session, *frame);
    if (!keep)
      break;
  }
  log_outcome(session, "close");
  session.stream.close();
}

std::optional<int> parse_port(std::string_view address) {
  const auto colon = address.rfind(':');
  if (colon == std::string_view::npos || colon + 1 >= address.size())
    return std::nullopt;
  int port = 0;
  for (char c : address.substr(colon + 1)) {
    if (c < '0' || c > '9')
      return std::nullopt;
    port = port * 10 + (c - '0');
    if (port > 65535)
      return std::nullopt;
  }
  return port;
}

} // namespace

int serve_stdio(const fs::path &repo) {
  run_session(net::Stream::stdio_stream(), repo, std::nullopt, {});
  return 0;
}

int serve_listen(std::string_view address, const fs::path &root,
                 std::string_view cert_path, std::string_view key_path) {
  net::ignore_sigpipe();
  auto port = parse_port(address);
  if (!port) {
    error_prefix();
    std::cout << "invalid listen address\n";
    return 1;
  }
  void *ctx = net::tls_server_ctx(cert_path, key_path);
  if (!ctx) {
    error_prefix();
    std::cout << "cannot load TLS certificate or key\n";
    return 1;
  }
  const net::Socket listener = net::tcp_listen(*port);
  if (listener == net::INVALID_SOCKET_VALUE) {
    error_prefix();
    std::cout << "cannot listen on port " << *port << "\n";
    net::tls_ctx_free(ctx);
    return 1;
  }
  info_prefix();
  std::cout << "listening on " << address << "\n";
  for (;;) {
    auto accepted = net::tcp_accept(listener);
    if (!accepted)
      break;
    void *ssl = net::tls_accept(ctx, *accepted);
    if (!ssl) {
      net::close_socket(*accepted);
      continue;
    }
    std::array<std::uint8_t, 32> exported{};
    std::string binding;
    if (net::tls_exporter(ssl, exported.data(), exported.size())) {
      binding.assign(reinterpret_cast<const char *>(exported.data()),
                     exported.size());
    }
    run_session(net::Stream::tls_stream(*accepted, ssl), std::nullopt, root,
                std::move(binding));
  }
  net::close_socket(listener);
  net::tls_ctx_free(ctx);
  return 0;
}

} // namespace vn::server
