/*{{{}}}*/
/*{{{  #includes*/
#ifdef CONFIG_H
#   include "config.h"
#endif

#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <pwd.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>

#include <h/envvar_str.h>
#include <h/os.h>
#include <lib/ori_add_lib.h>
/*}}}  */

/*{{{  expand leading ~ in pathnames*/
char *home_expand(char * const n)
{
  if (n[0]==HOME_CHAR)
   { char n_buff[_POSIX_PATH_MAX+1];
     char *n_ptr;
     int l;

     strcpy(n_ptr=n_buff,n);
     l=strlen(n)-1;
     switch (n[1])
      { case PATH_C:
        case '\0':
         /*{{{  replace by value of $HOME*/
         { static char *h=0;

           if (!h)
              h=getenv(HOME);
           if (h && l+strlen(h)<_POSIX_PATH_MAX)
            { n_ptr++;
              strcpy(n,h);
            }
           else
              n[0]='\0';
           break;
         }
         /*}}}  */
        default:
         /*{{{  try to get a passwd entry for it*/
         { char *s;
           struct passwd *x;

           s=n;
           while (*s && *s!=PATH_C)
            { s++;
              n_ptr++;
              l--;
            }
           *s='\0';
           x=getpwnam((char *)n+1);
#          ifndef NO_ENDPWENT
              endpwent();
#          endif
           if (x && l+strlen(x->pw_dir)<_POSIX_PATH_MAX)
              strcpy(n,x->pw_dir);
           else
            { n_ptr=n_buff;
              n[0]='\0';
            }
         }
         /*}}}  */
      }
     strcat(n,n_ptr);
   }

  return(n);
}
/*}}}  */
/*{{{  getpwent*/
/*{{{  variables*/
#ifdef NO_GETPWENT
   static uid_t uid_val;
#endif
/*}}}  */
/*{{{  start_getpwent*/
void start_getpwent(void)
{
#ifdef NO_GETPWENT
# ifndef UID_START_GETPWENT
#    define UID_START_GETPWENT 0
# endif
# ifndef UID_END_GETPWENT
#    define UID_END_GETPWENT 31
# endif
  uid_val=UID_START_GETPWENT;
# endif
}
/*}}}  */
/*{{{  next_getpwent*/
char const *next_getpwent(void)
{ struct passwd *x;

#ifdef NO_GETPWENT
   x=(uid_val>UID_END_GETPWENT)?0:getpwuid(uid_val++);
#else
   x=getpwent();
#endif

   return(x?x->pw_name:0);
}
/*}}}  */
/*{{{  end_getpwent*/
void end_getpwent(void)
{
# ifndef NO_ENDPWENT
     endpwent();
# endif
}
/*}}}  */
/*}}}  */
