+char *temp_file(const void *ctx, const char *extension, const char *srcname)
+{
+ char *f, *base, *suffix;
+ struct stat st;
+ unsigned int count = 0;
+
+ base = path_join(ctx, temp_dir(), take(path_basename(ctx, srcname)));
+ /* Trim extension. */
+ base[path_ext_off(base)] = '\0';
+ suffix = tal_strdup(ctx, extension);
+
+ do {
+ f = tal_strcat(ctx, base, suffix);
+ suffix = tal_fmt(base, "-%u%s", ++count, extension);
+ } while (lstat(f, &st) == 0);
+
+ if (tools_verbose)
+ printf("Creating file %s\n", f);
+
+ tal_free(base);
+ return f;
+}
+
+bool move_file(const char *oldname, const char *newname)
+{
+ char *contents;
+ int fd;
+ bool ret;
+
+ if (tools_verbose)
+ printf("Moving file %s to %s: ", oldname, newname);
+
+ /* Simple case: rename works. */
+ if (rename(oldname, newname) == 0) {
+ if (tools_verbose)
+ printf("rename worked\n");
+ return true;
+ }
+
+ /* Try copy and delete: not atomic! */
+ contents = grab_file(NULL, oldname);
+ if (!contents) {
+ if (tools_verbose)
+ printf("read failed: %s\n", strerror(errno));
+ return false;
+ }
+
+ fd = open(newname, O_WRONLY|O_CREAT|O_TRUNC, 0666);
+ if (fd < 0) {
+ if (tools_verbose)
+ printf("output open failed: %s\n", strerror(errno));
+ ret = false;
+ goto free;
+ }