/* ISC license. */

#include <unistd.h>
#include <sys/types.h>
#include <sys/swap.h>
#include <errno.h>

#include <skalibs/uint64.h>
#include <skalibs/bytestr.h>
#include <skalibs/buffer.h>
#include <skalibs/envexec.h>
#include <skalibs/stralloc.h>
#include <skalibs/djbunix.h>
#include <skalibs/skamisc.h>

#define USAGE "s6-swapoff [ -a ] [ device ]"

static int swapoffall (void)
{
  char buf[4096] ;
  buffer b ;
  stralloc sa = STRALLOC_ZERO ;
  int e = 0 ;
  int r ;
  int fd = open_readb("/proc/swaps") ;
  if (fd < 0) strerr_diefu1sys(111, "open_readb /proc/swaps") ;
  buffer_init(&b, &buffer_read, fd, buf, 4096) ;
  if (skagetln(&b, &sa, '\n') < 0) strerr_diefu1sys(111, "skagetln") ;
  for (;;)
  {
    size_t n ;
    sa.len = 0 ;
    r = skagetln(&b, &sa, '\n') ;
    if (r < 0) strerr_diefu1sys(111, "skagetln") ;
    if (!r) break ;
    n = byte_chr(sa.s, sa.len, ' ') ;
    if (n >= sa.len) strerr_dief1x(111, "invalid line in /proc/swaps") ;
    sa.s[n] = 0 ;
    if (swapoff(sa.s) < 0) { e++ ; strerr_warnwu2sys("swapoff ", sa.s) ; }
  }
  fd_close(fd) ;
  stralloc_free(&sa) ;
  return e ;
}

int main (int argc, char const *const *argv)
{
  static gol_bool const rgolb[] =
  {
    { .so = 'a', .lo = "all", .clear = 0, .set = 1 },
  } ;
  uint64_t wgolb = 0 ;
  unsigned int golc ;
  PROG = "s6-swapoff" ;
  golc = gol_main(argc, argv, rgolb, 1, 0, 0, &wgolb, 0) ;
  argc -= golc ; argv += golc ;
  if (wgolb & 1) _exit(swapoffall()) ;
  if (!argc) strerr_dieusage(100, USAGE) ;
  if (swapoff(argv[0]) == -1) strerr_diefu2sys(111, "swapoff ", argv[0]) ;
  _exit(0) ;
}
