/*
 *	Transparent Cryptographic File System (TCFS) for NetBSD 
 *	Author and mantainer: 	Luigi Catuogno [luicat@tcfs.unisa.it]
 *	
 *	references:		http://tcfs.dia.unisa.it
 *				tcfs-bsd@tcfs.unisa.it
 */

/*
 *	Base utility set v0.1
 *
 *	  $Source: /usr/src/tcfs-utils_0.1/lib/RCS/tcfs_getfspath.c,v $
 *	   $State: Exp $
 *	$Revision: 1.1 $
 *	  $Author: luicat $
 *	    $Date: 2000/01/10 10:38:19 $
 *
 */

static const char *RCSid="$id: $";

/* RCS_HEADER_ENDS_HERE */



#include <stdio.h>
#include <strings.h>
#include <stdlib.h>

#define TCFSTAB "/usr/tcfs/etc/tcfstab"

int tcfs_mount_getcipher (char *mountpoint)
{
	FILE *fp;
	char *label, *mountfield, *cipherfield;
	int found=0, ciphernumber=0;

	if (fp=fopen (TCFSTAB, "r"))
	{
	  while (!feof(fp) && !found)
	  {
	    char *line;

	    line=(char *)calloc(1024,sizeof(char));

	    fgets (line, 1024, fp);
	    while ((label=strsep(&line,":"))!=NULL && !found)
	    {
	      if (label)
	      {
		 mountfield=strsep(&line, ":");
		 if (mountfield)
		 {
		    if (!strcmp(mountfield, mountpoint))
		    {
		      cipherfield=strsep(&line, ":");
		      if (cipherfield)
		      {
		        ciphernumber=atoi(cipherfield);
		        found=1;
		      }
		    }
		 }
	      }
	    }
	  }
	}

	if (found)
	  return ciphernumber;

	return -1;
}

int tcfs_label_getcipher (char *label)
{
	int ciphernum;

	if (tcfs_get_label (label, NULL, &ciphernum))
	  return ciphernum;

        return -1;
}

int tcfs_getfspath (char *label2search, char *path)
{
	return tcfs_get_label (label2search, path, NULL);
}

int tcfs_get_label(char *label2search, char *path, int *ciphernumber)
{
	FILE *fp;
	char *label;
	int found=0;

	if(fp=fopen(TCFSTAB,"r"))
	{
		while ( !feof (fp) && !found )
		{
		  char *line;

		  line=(char *)calloc(1024,sizeof(char));

		  fgets (line, 1024, fp);
		  while ( (label=strsep (&line, ":")) !=NULL && !found)
		  {
		    if (label && !strcmp(label, label2search))
                    {
		      char *cipherfield, *pathfield;

		      pathfield=strsep(&line, ":");
		      if (path)
		      {
		        strcpy (path, pathfield);
			found=1;
		      }

		      if (ciphernumber && (cipherfield=strsep(&line, ":")) )
		      {
		        *ciphernumber=atoi(cipherfield);
			found=1;
                      }
		    }
                  } 
		 free (line);
		}
	}	  
	fclose (fp);

	return found;
}
