#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

void show_stat_info(char *fname, struct stat *buf);

int main(int argc, char *argv[])
{
    struct stat info;   
    if (argc>1) {
      if( stat(argv[1], &info) != -1 ){
            show_stat_info( argv[1], &info );
            return 0;
      }
    }
    else
      printf("Uzycie: %s nazwa_pliku\n",argv[0]);  
    return 1;
}

char mode_to_type(int mode)
{
	if ( S_ISDIR(mode) ) return 'd';
	if ( S_ISCHR(mode) ) return 'c';
	if ( S_ISBLK(mode) ) return 'b';
	if ( S_ISREG(mode) ) return 'f';
	if ( S_ISFIFO(mode) ) return 'i';
	if ( S_ISLNK(mode) ) return 'l';
	if ( S_ISSOCK(mode) ) return 's';
	return '?';
}

void mode_to_letters( int mode, char str[] )
{
	strcpy( str, "---------" );
	if ( mode & S_IRUSR ) str[0] = 'r';
	if ( mode & S_IWUSR ) str[1] = 'w';
	if ( mode & S_IXUSR ) str[2] = 'x';
	if ( mode & S_IRGRP ) str[3] = 'r';
	if ( mode & S_IWGRP ) str[4] = 'w';
	if ( mode & S_IXGRP ) str[5] = 'x';
	if ( mode & S_IROTH ) str[6] = 'r';
	if ( mode & S_IWOTH ) str[7] = 'w';
	if ( mode & S_IXOTH ) str[8] = 'x';
	if ( mode & S_ISUID ) str[2] = 's';
	if ( mode & S_ISGID ) str[5] = 's';
	if ( mode & S_ISVTX ) str[8] = 't';
}

char * zinterpretujRozmiar(off_t size)
{
	double rozm = size;
	unsigned int rozmBuf = 20;
	char * buf = malloc(sizeof(char *) * rozmBuf);
	char * sufiksy[] = {"bajtow", "kilobajtow", "megabajtow", "gigabajtow", "terabajtow" };
	int i;
	
	bzero(buf, rozmBuf);
	for(i = 0; rozm > 1024 && i < 5; ++i)
		rozm = rozm / 1024;
	snprintf(buf, rozmBuf, "%.2f %s", rozm, sufiksy[i]);
	return buf;
}

void show_stat_info(char *fname, struct stat *buf)
{
	char buf2[10];
	mode_to_letters(buf->st_mode, buf2);         /* type + mode */
	printf("File name: %s\n", fname);
	printf("File type: %c\n", mode_to_type(buf->st_mode));         /* type + mode */
	printf("File mode: %s\n", buf2);         /* type + mode */
	printf("Links: %d\n", (int) buf->st_nlink);        /* # links     */
	printf("UID: %s (%d)\n", getpwuid(buf->st_uid)->pw_name, buf->st_uid);          /* user id     */
	printf("GID: %s (%d)\n", getgrgid(buf->st_gid)->gr_name, buf->st_gid);          /* group id    */
	printf("Size: %s (%ld bytes)\n", zinterpretujRozmiar(buf->st_size), buf->st_size);     
	printf("Accestime: %s", ctime(&buf->st_atime));        /* modified    */
	printf("Modtime: %s", ctime(&buf->st_mtime));        /* modified    */
	printf("Createtime: %s", ctime(&buf->st_ctime));        /* modified    */
}
