-my $dir = dirname($pi_config);
-mkpath($dir); # will croak on fatal errors
-my ($fh, $pi_config_tmp) = tempfile('pi-init-XXXXXXXX', DIR => $dir);
-my $perm;
+require File::Basename;
+my $dir = File::Basename::dirname($pi_config);
+require File::Path;
+File::Path::mkpath($dir); # will croak on fatal errors
+
+# first, we grab a flock to prevent simultaneous public-inbox-init
+# processes from trampling over each other, or exiting with 255 on
+# O_EXCL failure below. This gets unlocked automatically on exit:
+require PublicInbox::Lock;
+my $lock_obj = { lock_path => "$pi_config.flock" };
+PublicInbox::Lock::lock_acquire($lock_obj);
+
+# git-config will operate on this (and rename on success):
+require File::Temp;
+my $fh = File::Temp->new(TEMPLATE => 'pi-init-XXXXXXXX', DIR => $dir);
+
+# Now, we grab another lock to use git-config(1) locking, so it won't
+# wait on the lock, unlike some of our internal flock()-based locks.
+# This is to prevent direct git-config(1) usage from clobbering our
+# changes.
+my $lockfile = "$pi_config.lock";
+my $lockfh;
+sysopen($lockfh, $lockfile, O_RDWR|O_CREAT|O_EXCL) or do {
+ warn "could not open config file: $lockfile: $!\n";
+ exit(255);
+};
+my $auto_unlink = UnlinkMe->new($lockfile);
+my ($perm, %seen);