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


void usageAndExit(void)
{
	printf("Usage: zad2 PROGRAM\n");
	exit(1);
}

char * polaczNapisy(char * a, char * b)
{
	char * c;
	unsigned int size = 0;

	size = sizeof(char) * (strlen(a) + strlen(b) + 2);
	c = malloc(size);
	bzero(c, size);
	snprintf(c, size, "%s/%s", a, b);
	return c;
}

int sprawdzCzyPlikIstnieje(char * file)
{
	uid_t euid;
	uid_t egid;
	struct stat buf;

	euid = geteuid();
	egid = getegid();
	if (stat(file, &buf) == -1) return 0;
	if (( buf.st_mode & S_IXUSR ) && (buf.st_uid == euid)) return 1;
	if (( buf.st_mode & S_IXGRP ) && (buf.st_gid == egid)) return 1;
	if (buf.st_mode & S_IXOTH) return 1;
	return 0;
}

void sprawdzSciezke(char * p, char * prog)
{
	char * fullPath;

	fullPath = polaczNapisy(p, prog);
	if (sprawdzCzyPlikIstnieje(fullPath))
	{
		printf("%s\n", fullPath);
		exit(0);
	}
}

int main(int argc, char *argv[])
{
	char * path;
	int i = 0;
	int poczatek = 0;
	
	if (argc != 2) usageAndExit();

	path = getenv("PATH");
	for (i = 0; path[i] != '\0'; ++i)
	{
		if (path[i] == ':')
		{
			path[i] = '\0';
			sprawdzSciezke(path + poczatek, argv[1]);
			poczatek = i + 1;
		} else {
		}
	}
	sprawdzSciezke(path + poczatek, argv[1]);
	exit(0);
}

