#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <assert.h>

int main(int argc, char **argv) {
	char *buf;
	FILE *fp;
	size_t bytes;
	struct stat st;
	char *fname;
	long offset;

	if (argc != 4) {
		fprintf(stderr, "Usage: %s <fname> <offset> <newbyte>\n", argv[0]);
		exit(1);
	}

	fname = argv[1];

	if ((fp = fopen(fname, "rb")) == NULL)
		return 1;
	
	if ((stat(fname, &st)) == (-1))
		return 1;

	offset = atol(argv[2]);
	buf = (char *) malloc(st.st_size);

	bytes = fread(buf, 1, st.st_size, fp);
	fclose(fp);

	assert(bytes == st.st_size);

	assert(buf[offset] == 0x16);
	assert(buf[offset+1] == 0x0);
	assert(buf[offset+2] == 0x0);
	assert(buf[offset+3] == 0x0);

	buf[offset] = atol(argv[3]);

	if ((fp = fopen("textrel.so", "wb")) == NULL)
			return 1;

	bytes = fwrite(buf, 1, st.st_size, fp);
	fchmod(fileno(fp), st.st_mode);
	fclose(fp);
	free(buf);
	return 0;
}
