#!/usr/bin/env zsh
set -euo pipefail

source_file="${0}.swift"
uid="$(id -u)"
base_cache_dir="${TMPDIR:-/tmp}/sovereign-memory-afm-${uid}"

umask 077
if ! mkdir "${base_cache_dir}" 2>/dev/null; then
  if [[ -L "${base_cache_dir}" ]]; then
    echo "Refusing symlink cache directory: ${base_cache_dir}" >&2
    exit 1
  fi
  if [[ ! -d "${base_cache_dir}" ]]; then
    echo "Cache path exists but is not a directory: ${base_cache_dir}" >&2
    exit 1
  fi
  owner_uid="$(stat -f %u "${base_cache_dir}")"
  if [[ "${owner_uid}" != "${uid}" ]]; then
    echo "Refusing cache directory not owned by current user: ${base_cache_dir}" >&2
    exit 1
  fi
fi

chmod 700 "${base_cache_dir}"

source_mtime="$(stat -f %m "${source_file}")"
binary="${base_cache_dir}/native-afm-helper-${source_mtime}"

if [[ -L "${binary}" ]]; then
  echo "Refusing symlink cache binary: ${binary}" >&2
  exit 1
fi

if [[ -x "${binary}" ]]; then
  owner_uid="$(stat -f %u "${binary}")"
  if [[ "${owner_uid}" != "${uid}" ]]; then
    echo "Refusing cache binary not owned by current user: ${binary}" >&2
    exit 1
  fi
else
  tmp_binary="$(mktemp "${base_cache_dir}/.native-afm-helper-${source_mtime}.XXXXXX")"
  xcrun --sdk macosx swiftc -parse-as-library "${source_file}" -o "${tmp_binary}"
  chmod 700 "${tmp_binary}"
  mv -f "${tmp_binary}" "${binary}"
fi

exec "${binary}"
