
/* usage: joinf_xattr srcdir 
 * 
 * this "undoes" splitf_xattr, setting xattrs in srcdir
 * based on the xattr containers appearing in stdin.
 *
 * Returns -1 if errors detected, and 0 otherwise.
 *
 */

#include "util.h"
#include "xattr_util.h"


static char magic[8] = { 0xb7, 0x0e, 0xbf, 0xb2, 0xc2, 0x91, 0xf2, 0x92 };


void usage()
{
   fprintf(stderr, "usage: joinf_xattr srcdir\n");
}


static char extension[MAXLEN];
static char itemname[MAXLEN];


int main(int argc, char **argv)
{
   char *srcname;
   struct stat srcstat, itemstat;
   int srcname_len;
   char mbuf[8];

   int c, k;
   int ret, retval;

   retval = 0;

   if (argc == 2) {
      srcname = argv[1];
   }
   else {
      usage();
      return -1;
   }

   srcname_len = strlen(srcname);
   if (srcname[srcname_len-1] == '/') {
      srcname[srcname_len-1] = '\0';
      srcname_len--;
   }

   if (lstat(srcname, &srcstat) || !S_ISDIR(srcstat.st_mode)) {
      usage();
      return -1;
   }

   
   if (fread(mbuf, 1, 8, stdin) != 8 || memcmp(magic, mbuf, 8)) {
      fprintf(stderr, "bad file format\n");
      return -1;
   }

   for (;;) {

      c = getchar();
      if (c == EOF) return retval;

      k = 0;
      for (;;) {
         if (c == EOF) return -1;
         if (k >= MAXLEN) {
            fprintf(stderr, "buffer overflow\n");
            return -1;
         }
         extension[k] = c; 
         k++;
         if (c == 0) break;
         c = getchar();
      }

      if (snprintf(itemname, MAXLEN, "%s%s", srcname, extension) >= MAXLEN) 
         overflow();

      ret = 0;

      if (lstat(itemname, &itemstat) || 
          !(S_ISDIR(itemstat.st_mode) || S_ISREG_OR_LNK(itemstat.st_mode))) {

         ret = skip_xattr("");
      

      }
      else {

         ret = join_xattr(itemname, &itemstat, "");


      }

      if (ret) {
         if (ret == -1) {
            fprintf(stderr, "recoverble error processing %s -- continuing\n", itemname); 
            retval = -1;
         }
         else {
            fprintf(stderr, "unrecoverble error processing %s -- aborting\n", itemname); 
            return -1;
         }

      }
   }
}
