/* chmod -- change the permissions of a file */
/* chown -- change the owner and group of a file */
/* written by Eric R. Smith and placed in the public domain */

#include <types.h>
#include <stat.h>
#include <osbind.h>
#include <mintbind.h>
#include <limits.h>
#include <errno.h>
#include <unistd.h>
#include "lib.h"

extern int __mint;

int chmod(_path, mode)
       const char *_path;
       int   mode;
{
       int  dosattrib = 0, r;
       char path[PATH_MAX];
       struct stat stb;

       (void)_unx2dos(_path, path);

	if (__mint >= 9) {	/* use MiNT Fchmod function */
		r = Fchmod(path, mode);
		if (r) {
			errno = -r;
			return -1;
		}
		return 0;
	}

/* The following lines ensure that the archive bit isn't cleared */
	r = Fattrib(path, 0, dosattrib);
 	if (r > 0 && (r & FA_CHANGED))
		dosattrib |= FA_CHANGED;

#if 0
       if (!(mode & S_IREAD))
               dosattrib |= FA_HIDDEN;
#endif
       if (!(mode & S_IWRITE))
               dosattrib |= FA_RDONLY;
       r = Fattrib(path, 1, dosattrib);
       if (r < 0) {
/* GEMDOS doesn't allow chmod on a directory, so pretend it worked */
               if (!stat(_path, &stb)) {
	            if ( (stb.st_mode & S_IFMT) == S_IFDIR )
			return 0;
               }
               errno = -r;
               return -1;
       }
       return 0;
}

/*
 * chown: this is faked if MiNT is not running
 */

int chown(_name, uid, gid)
       const char *_name;
       int uid, gid;
{
	int r;
	char name[PATH_MAX];

	if (__mint >= 9) {
		(void)_unx2dos(_name, name);
		r = Fchown(name, uid, gid);
		if (r) {
			errno = -r;
			return -1;
		}
		return 0;
	}
	return 0;
}
