/* Test 17 -> Checks whether the truncate function in the library
* works properly
**/

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <string.h>
#include <dlfcn.h>
#include <stdlib.h>


int main()
{
   int fd1 = -1, fd2 = -1;
   int err;
   void * handle = NULL;
   char buf[4096];
   char new_buf[4096];
   int i=0;
   int data_read = 0;
   off_t cur=0;

    handle = dlopen("/lib/libc.so.6",  RTLD_LAZY);
    if (handle == NULL) {
	fprintf(stderr, "%s", dlerror());
	return -1;
    }
    int (*o_open)(const char *, int) = (int (*)(const char *, int)) dlsym(handle, "open");
    ssize_t (*o_read)(int, void *, size_t) = (ssize_t (*)(int, void *, size_t)) dlsym(handle, "read");
    ssize_t (*o_write)(int, void *, size_t) = (ssize_t (*)(int, void *, size_t)) dlsym(handle, "write");
    off_t (*o_lseek)(int, off_t, int) = (off_t (*)(int, off_t, int)) dlsym(handle, "lseek");
    int (*o_close)(int) = (int (*)(int)) dlsym(handle, "close");


/* Bootstrap the file with libfsprotect.c */
   fd1 = open("file5", O_RDWR);
   if(fd1 == -1) {
         return -1;
   }
   err = close(fd1);
   if(err == -1)
        return -1;
   
printf("past Bootstrapping-----------------------------------------------------\n");
/* Open and truncate the file */
   err = truncate("file5", 8192);
   printf("err = %d\n", err);	
   if(err == -1)
        return -1;

printf("past truncating----------------------------------------------------------\n");

/* Read through libc and see if the file was truncated */ 
   fd1 = (*o_open)("file5", O_RDONLY);  
   if(fd1 == -1) {
   	 printf("couldn't open the file using libc\n");
         return -1;
   }

printf("opened file fine\n");


   cur = (*o_lseek)(fd1, 0, SEEK_END);
   if(cur != 8192) {
         (*o_close)(fd1);
	 printf("not truncated to the correct size\n");
         return -1;
   }
   (*o_close)(fd1);

   printf("seek worked correctly\n");

/* Open the file again and see that the read works properly */
   fd1 = open("file5", O_RDWR);
   if(fd1 == -1) {
   	printf("failing while trying to open again\n");
         return -1;
   }
   for(i=0; i<2; i++) {
      err = read(fd1, buf, 4096);
      if(err == -1) {
           close(fd1);
	   printf("failed while reading\n");
           return -1;
      } 
   }  
   err = close(fd1);
   if(err == -1)
   	printf("failed while closing the file\n");
        return -1;
 
   return 0;
}
