/*
 * SPDX-FileCopyrightText: 2026 Didier Kryn <kryn@in2p3.fr>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
/* Tell if a disk is used by any of the partitions listed in mtab */
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <limits.h>
#include <mntent.h>
#include "slash_sys.h"

static char disk_list[256] = {'\0'};

int istab(const char *name, size_t len)
{
  /* we rely on len being the length of name */
  char *c;
  c = strstr(disk_list, name);
  if(!c) return 0;
  /* check the found name is not continued */
  return ( c[len] == '\0' || c[len] ==' ' );
}

void addtab(const char *name, size_t len)
{
  /* we rely on len being the length of name */
  static char *c1 = disk_list;
  const static char *c2 = disk_list + sizeof(disk_list) - 1;

  if( istab(name, len) ) return;
  if( (c1+len) > c2 ) return; /* list size exhausted */
  strcpy(c1, name);
  c1 += len;
  if( c1 < (c2) )
    {
      *c1 = ' ';
      c1++;
      *c1 = '\0';
    }
 }

int osuse(const char *name)
{
  char buf[PATH_MAX];
  const char *list = disk_list;
  dev_prop dp;
  FILE *mntfile;
  int q;
  
  /* The name might denote a disk, but also a partition.
     Therefore find the disk. */
  if( !(get_device_prop(devpath(name, buf), "disk", &dp)) ) return -1;
  /* return -1 if device is neither disk nor partition */

  if( !(mntfile = setmntent("/proc/mounts", "r")) ) return -2;
  if(lsmtab(mntfile, addtab, name)) return 2;  /* already mounted  */
  else return istab(dp.dn, strlen(dp.dn));     /* 1 or 0 ==> disk used or not */
}
