/*
 * $Id: ad_attr.c,v 1.4.8.7 2004/09/06 09:38:22 didg Exp $
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

#include <string.h>
#include <atalk/adouble.h>

#define FILEIOFF_ATTR 14
#define AFPFILEIOFF_ATTR 2

int ad_getattr(const struct adouble *ad, u_int16_t *attr)
{
   *attr = 0;
        
   if (ad->ad_version == AD_VERSION1) {
       if (ad_getentryoff(ad, ADEID_FILEI)) {
           memcpy(attr, ad_entry(ad, ADEID_FILEI) + FILEIOFF_ATTR,
	          sizeof(u_int16_t));
       }
   }
#if AD_VERSION == AD_VERSION2
   else if (ad->ad_version == AD_VERSION2) {
       if (ad_getentryoff(ad, ADEID_AFPFILEI)) {
           memcpy(attr, ad_entry(ad, ADEID_AFPFILEI) + AFPFILEIOFF_ATTR,
	          sizeof(u_int16_t));
       }
   }	   
#endif
   else 
      return -1;

   return 0;
}

/* ----------------- */
int ad_setattr(const struct adouble *ad, const u_int16_t attr)
{
   if (ad->ad_version == AD_VERSION1) {
       if (ad_getentryoff(ad, ADEID_FILEI)) {
           memcpy(ad_entry(ad, ADEID_FILEI) + FILEIOFF_ATTR, &attr,
	           sizeof(attr));
       }
   }	   
#if AD_VERSION == AD_VERSION2
   else if (ad->ad_version == AD_VERSION2) {
       if (ad_getentryoff(ad, ADEID_AFPFILEI)) {
            memcpy(ad_entry(ad, ADEID_AFPFILEI) + AFPFILEIOFF_ATTR, &attr,
  	            sizeof(attr));
       }
   }	   
#endif
   else 
      return -1;

   return 0;
}

/* -------------- 
 * save file/folder ID in AppleDoubleV2 netatalk private parameters
 * return 1 if resource fork has been modified
*/
#if AD_VERSION == AD_VERSION2
int ad_setid (struct adouble *adp, const dev_t dev, const ino_t ino , const u_int32_t id, const cnid_t did, const void *stamp)
{
    if (adp->ad_flags == AD_VERSION2  && ad_getentryoff(adp, ADEID_PRIVDEV) &&
                sizeof(dev_t) == ADEDLEN_PRIVDEV && sizeof(ino_t) == ADEDLEN_PRIVINO) 
    {
        ad_setentrylen( adp, ADEID_PRIVDEV, sizeof(dev_t));
        memcpy(ad_entry( adp, ADEID_PRIVDEV ), &dev, sizeof(dev_t));

        ad_setentrylen( adp, ADEID_PRIVINO, sizeof(ino_t));
        memcpy(ad_entry( adp, ADEID_PRIVINO ), &ino, sizeof(ino_t));

	ad_setentrylen( adp, ADEID_PRIVID, sizeof(id));
        memcpy(ad_entry( adp, ADEID_PRIVID ), &id, sizeof(id));

        ad_setentrylen( adp, ADEID_DID, sizeof(did));
        memcpy(ad_entry( adp, ADEID_DID ), &did, sizeof(did));

        ad_setentrylen( adp, ADEID_PRIVSYN, ADEDLEN_PRIVSYN);
        memcpy(ad_entry( adp, ADEID_PRIVSYN ), stamp, ADEDLEN_PRIVSYN);
        return 1;
    }
    return 0;
}

#endif

/* ----------------- 
 * set resource fork filename attribute.
*/
int ad_setname(struct adouble *ad, const char *path)
{
    if (ad_getentryoff(ad, ADEID_NAME)) {
        ad_setentrylen( ad, ADEID_NAME, strlen( path ));
        memcpy(ad_entry( ad, ADEID_NAME ), path, ad_getentrylen( ad, ADEID_NAME ));
        return 1;
    }
    return 0;
}
