#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>

#define NEW_DIR "/usr/foo"
#define REL_READ_FILE "../lib/libtcl.so"

int new_dir_rel_read_file(void)
{
	printf("Checking if you can read a relative file in an new dir...\n");

	int dfd, fd, retval = 0;
	static char buf[5];
	if((dfd = open(NEW_DIR, O_RDONLY)) == -1)
		goto out;
	if(fchdir(dfd) == -1)
		goto close_out;
	if((fd = open(REL_READ_FILE, O_RDONLY)) == -1)
		goto close_out;
	if(read(fd, buf, sizeof(buf) - 1) != sizeof(buf) - 1)
		goto close_close_out;
	retval = 1;
	printf("\tthe next three letters should be ELF: %s.\n", buf+1);

close_close_out:
	close(fd);
close_out:
	close(dfd);
out:
	if(!retval)
		perror(__func__);
	return retval;
}

int main(int argc, char *argv[])
{
	printf("Attempting to create " NEW_DIR "...\n");
	if(mkdir(NEW_DIR, 0755) == -1) {
		perror(NEW_DIR " could not be created");
		return -1; 
	}
	else
		printf("\t" NEW_DIR " successfully created.\n");

	new_dir_rel_read_file();

	return 0;
}
