#include <stdio.h>
#include <stdlib.h>
#include <readline/readline.h>
#include <unistd.h>
#include <string.h>

static char *filename;

int pretype(void)
{
	rl_insert_text(filename);
	return 0;
}

int main(int argc, char *argv[])
{
	int i;
	char *newname, *prompt;

	if (argc < 2) {
		fprintf(stderr, "Usage: %s SOURCE...\nInteractively rename SOURCE.\n", argv[0]);
		return EXIT_FAILURE;
	}

	for (i = 1; i < argc; ++i) {
		filename = argv[i];

		if (access(filename, W_OK)) {
			perror("access");
			return EXIT_FAILURE;
		}
		
		if ((prompt = calloc(strlen(filename) + 5, sizeof(char))) == NULL) {
			perror("calloc");
			return EXIT_FAILURE;
		}
		
		if (argc > 2)
			sprintf(prompt, "%s => ", filename);
		else
			strcpy(prompt, "=> ");

		rl_startup_hook = pretype;
		newname = readline(prompt);
		rl_startup_hook = NULL;
		free(prompt);
		prompt = NULL;

		if (!access(newname, F_OK) && strcmp(prompt = readline("File already exists. Overwrite? [y/n] "), "y") != 0)
			puts("Cancelled.");
		else if (rename(filename, newname) == -1) {
			perror("rename");
			return EXIT_FAILURE;
		}

		free(newname);
		if (prompt) {
			free(prompt);
			prompt = NULL;
		}
	}

	return EXIT_SUCCESS;
}
