/*
    NON-MSDOS file name resulution emulation function
*/

#ifndef MSDOS
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ctype.h>
#include "icrss.h"

static FILE
    *fp = NULL;                                 /* echo program pipe */
    
static char *filename (char *fname)             /* return pointer into */
{                                               /* fname, just beyond */
    register char                               /* directory name */
        *cp;
        
    if ( 
           (cp = strrchr (fname, DIRSEP))
           &&
           *(cp + 1)
        )
         return (cp + 1);
         
    return (fname);
}

static int make_attrib (char *fname)            /* make DOS attribs */
{
    register int
        ret = 0;                                /* returned attribute */
    struct stat
        statbuf;                                /* stat () buffer */
        
    if (stat (fname, &statbuf) == -1)           /* if not stat-able .. */
        return (0xdead);                        /* dead flag return */

    if (statbuf.st_mode & S_IFDIR)              /* directory entry */
        ret |= A_SUBDIR;
        
    if (!(statbuf.st_mode & S_IWRITE))          /* non-writable entry */
        ret |= A_RDONLY;
        
    if (*fname == '.' &&                        /* .file */
        strcmp (fname, ".") &&
        strcmp (fname, "..")
       )
        ret |= A_HIDDEN;
    
    return (ret);                               /* return attrib */
}

                                                /* dos_findfirst emulator */
                                                /* ignores attribute! */
unsigned _dos_findfirst(char * fspec, unsigned attrib,
    struct _find_t * fileinfo)
{
    char
        buf[_MAX_PATH];                         /* filename buf */

    sprintf (buf, "echo %s", fspec);            /* open new pipe */
    
    if (!(fp = popen(buf, "r")) ||              /* read first name */
        !fscanf (fp, "%s", buf)
       )
    {
        fclose (fp);
        return -1;
    }

    strcpy (fileinfo->name, filename (buf));    /* set name and attribute */
    
                                                /* if non-existing.. */
    if ((fileinfo->attrib = make_attrib (buf)) == 0xdead)
        return (-1);
        
    return (0);                                 /* return success */
}

unsigned _dos_findnext(struct _find_t * fileinfo)
{
    char
        buf[_MAX_PATH];

    if (! fscanf (fp, "%s", buf) ||             /* if no more strings, */
        feof (fp)                               /* or at EOF in pipe: */
       )
    {
        fclose (fp);                            /* all done, */
        return -1;
    }

    strcpy (fileinfo->name, filename (buf));    /* set name, attrib */
    fileinfo->attrib = make_attrib (buf);       /* file should exist now */
    return (0);                                 /* return success */
}
#endif
