/*
 * readlink.c
 *
 * Copyright (C) 1993 Alain Knaff
 */
#define readlink x
#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE

#include "sysincludes.h"
#undef readlink

int readlink(__const char *file_name, char *buf, size_t len)
{
  int st;
  int olderrno;

  _zlibc_init();
  st = zlib_real_readlink(file_name,buf,len);

  if ( st >= 0 || errno != ENOENT )
    return st;
  {
    char newname[MAXPATHLEN + MAXEXTLEN + 1];
    olderrno = errno;

    zlib_initialise();
    if ( zlib_mode & CM_DISAB )
      return st;
    if ( (zlib_getfiletype(file_name,-1) & PM_READ_MASK) == PM_LEAVE_COMPR)
      return st;


    if ( zlib_mode & CM_VERBOSE )
      fprintf(stderr,"readlinking %s\n", file_name);


    strncpy(newname,file_name,1024);
    strcat(newname,zlib_ext);

    st = zlib_real_readlink(newname, buf, len);
    if ( st < 0 ){
      errno = olderrno;
      return st;
    }

    if(!strncmp(buf + st - zlib_extlen, zlib_ext, zlib_extlen))
      buf[st-zlib_extlen] = 0;
    /* the file exists with z extension, ignore error */
    errno=0;
    return st;
  }
}
