/*
 * SPDX-FileCopyrightText: 2026 Didier Kryn <kryn@in2p3.fr>
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
*/
#include <sys/types.h>
#include <stdio.h>
/* #include <libgen.h> /* if debugging: declare basename() */
#include <string.h>
#include <limits.h>
#include <dirent.h>
#include "slash_sys.h"
size_t strLcpy(char *dst, const char *src, size_t dest_size);

/* search for disk, if slaves are found, search recursively */
/* this is to find all disks involved in the current block-device */
/* the current block device may be either a disk or a partition */
/* when a disk is found, invoque callback function */
void lookup_disk(char *device_path, void (*callback)(const char *, size_t))
{
  dev_prop dp;
  char *dpath;
  char buf[PATH_MAX];
  int notdisk;

  dp.dt[0] = dp.dn[0] = '\0';
  /* Find a disk device uptree -- or just there! because this device is not
     necessarily a partition; it could be a metadisk that we shouldn't miss. */
  dpath = get_device_prop(device_path, "disk", &dp );
      
  if(dpath)
    {
      /* Found a disk device. Add to the list and follow up with slave disks  */
      /* Remember an md raid array and a dm logical volume have DEVTYPE=disk. */
      /* but their slaves subdirectory contains symlinks to the actual disks. */
      /* while normal disks have an empty slaves subdirectory.                */
      DIR *sld;
      char lbuf[PATH_MAX];
      char *spath, *lpath;
      /*
        printf("lookup_disk working on %s\n", basename(dpath));
        fflush(stdout);
      */
      callback(dp.dn, strlen(dp.dn)); /* Do whatever with the name and length */
      spath = canonpath(dpath, "slaves", buf);
      if( spath && (sld=opendir(spath)) ) /* "slaves" dir exists and is open */
	{
	  struct dirent *de;
	  while( (de=readdir(sld)) )
	    {
	      size_t len, size;
	      if(de->d_name[0] == '.') continue; /* skip ".*"   */
	      if(de->d_type & DT_LNK)
		{
                  /*
                    printf("lookup_disk following symlink %s in %s\n",
                    de->d_name, spath);
                    fflush(stdout);
                  */
		  lpath = canonpath(spath, de->d_name, lbuf);
		  if(lpath) lookup_disk(lpath, callback); /* recurse on slave */
		}
	    }
	  closedir(sld);
	}
    }
}


