# include "photdbc.h"

check_directory (char *basefile) {
  
  FILE *f;
  char *c, dir[256], filename[256];
  struct stat filestat;
  uid_t fuid, uid;
  gid_t fgid, gid;
  int status, cmode;

  uid = getuid();
  gid = getgid();

  /* check permission to write to directory */
  sprintf (filename, "%s\0", basefile);
  c = strrchr (filename, '/');
  if (c == (char *) NULL) {
    strcpy (dir, ".");
  } else {
    *c = 0;
    strcpy (dir, filename);
  }
  status = stat (dir, &filestat);
  if (status == -1) {
    fprintf (stderr, "directory %s does not exist, creating...\n", dir);
    cmode = S_IRWXU | S_IRWXG | S_IRWXO;
    status = mkdir (dir, cmode);
    if (status == -1) {
      fprintf (stderr, "ERROR: can't create %s\n", dir);
      exit (1);
    }
  } 
  status = stat (dir, &filestat);
  if (((uid == filestat.st_uid) && (filestat.st_mode & S_IRWXU)) ||
      ((gid == filestat.st_gid) && (filestat.st_mode & S_IRWXG)) || 
      (filestat.st_mode & S_IRWXO)) {
  } else {
    fprintf (stderr, "ERROR: can't write to %s\n", dir);
    exit (1);
  }
}

/* uses cp only */
make_backup (char *filename) {

  int status, cmode;
  struct stat filestat;
  char line [256];

  status = stat (filename, &filestat);
  if (status == 0) { /* file exists, make backup copy */
    sprintf (line, "cp %s %s~\0", filename, filename);
    status = system (line);
    if (status) {
      fprintf (stderr, "ERROR: unable to create %s~, exiting\n", filename);
      exit (1);
    }
    cmode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
    sprintf (line, "%s~\0", filename);
    chmod (line, cmode);
  }
  
}
