/* ISC license. */

#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>

#include <skalibs/posixplz.h>
#include <skalibs/bitarray.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>

#include <s6/ftrigr.h>
#include <s6/supervise.h>

static int registerit (ftrigr *a, uint32_t *id, char *fn, size_t len, stralloc *sa, tain const *deadline, tain *stamp)
{
  memcpy(fn + len, "/" S6_SUPERVISE_EVENTDIR, sizeof(S6_SUPERVISE_EVENTDIR) + 1) ;
  if (sarealpath(sa, fn) == -1 || !stralloc_0(sa)) return 0 ;
  sa->len = 0 ;
  return ftrigr_subscribe(a, id, 0, 0, sa->s, "x", deadline, stamp) ;
}

/*
  options: bit 0: wait for s6-supervise to exit
*/

int s6_supervise_unlink_names (char const *scdir, char const *const *names, size_t n, uint32_t options, tain const *deadline, tain *stamp)
{
  size_t scdirlen = strlen(scdir) ;
  size_t ntotal = n ;
  unsigned char locked[bitarray_div8(n)] ;
  unsigned char logged[bitarray_div8(n)] ;
  if (!n) return 0 ;
  memset(locked, 0, bitarray_div8(n)) ;
  memset(logged, 0, bitarray_div8(n)) ;

  if (options & 1) for (size_t i = 0 ; i < n ; i++)
  {
    struct stat st ;
    size_t nlen = strlen(names[i]) ;
    int h ;
    char fn[scdirlen + nlen + 6] ;
    memcpy(fn, scdir, scdirlen) ;
    fn[scdirlen] = '/' ;
    memcpy(fn + scdirlen + 1, names[i], nlen + 1) ;
    h = s6_svc_ok(fn) ;
    if (h < 0) return -1 ;
    if (h) bitarray_set(locked, i) ;
    memcpy(fn + scdirlen + 1 + nlen, "/log", 5) ;
    if (stat(fn, &st) < 0)
    {
      if (errno != ENOENT) return -1 ;
    }
    else
    {
      int r ;
      if (!S_ISDIR(st.st_mode)) return (errno = ENOTDIR, -1) ;
      r = s6_svc_ok(fn) ;
      if (r < 0) return -1 ;
      if (r != h) return (errno = EINVAL, -1) ;
      bitarray_set(logged, i) ;
      ntotal++ ;
    }
  } 

  {
    ftrigr a = FTRIGR_ZERO ;
    stralloc sa = STRALLOC_ZERO ;
    unsigned int m = 0 ;
    uint32_t ids[ntotal] ;
    if (options & 1 && !ftrigr_startf(&a, deadline, stamp)) return -1 ;
    for (size_t i = 0 ; i < n ; i++)
    {
      size_t nlen = strlen(names[i]) ;
      char fn[scdirlen + nlen + 6 + sizeof(S6_SUPERVISE_EVENTDIR)] ;
      memcpy(fn, scdir, scdirlen) ;
      fn[scdirlen] = '/' ;
      memcpy(fn + scdirlen + 1, names[i], nlen) ;
      if (options & 1 && bitarray_peek(locked, i))
      {
        if (registerit(&a, ids + m, fn, scdirlen + 1 + nlen, &sa, deadline, stamp)) m++ ;
        if (bitarray_peek(logged, i))
        {
          memcpy(fn + scdirlen + 1 + nlen, "/log", 4) ;
          if (registerit(&a, ids + m, fn, scdirlen + 5 + nlen, &sa, deadline, stamp)) m++ ;
        }
      }
      fn[scdirlen + 1 + nlen] = 0 ;
      unlink_void(fn) ;
    }
    s6_svc_writectl(scdir, S6_SVSCAN_CTLDIR, "an", 2) ;
    if (options & 1)
    {
      stralloc_free(&sa) ;
      ftrigr_wait_and(&a, ids, m, deadline, stamp) ;
      ftrigr_end(&a) ;
    }
    return m ;
  }
}
