#!/usr/bin/perl -w
# nailing-cargo: wrapper to use unpublished local crates
# SPDX-License-Identifier: AGPL-3.0-or-later
our $usage = <<'END';

usages:

  nailing-cargo <nailing-opts> <cargo-opts> [--] <subcmd>...
  nailing-cargo <nailing-opts> --- <cargo> <cargo-opts> [--] <subcmd>...
  nailing-cargo <nailing-opts> --- [--] <build-command>...

options:

  -v  Increase verbosity.  (Default is 1)
  -q  Set verbosity to 0
  -D  Increase amount of debugging dump.
  -n  "No action": stop after writing Cargo.toml.nailing~
      everywhere, and do not run any build command

  -c  Do add cargo command line options      } default is add if
  -C  Do not add cargo command line options  }  command is cargo

  -o --online                     -O --offline
  -u --cargo-lock-update          -U --no-cargo-lock-update

  -T<arch>  --target=<arch>       Specify target architecture
  -h --help                       Print this message
  --doc --man --manual            Display complete manual (in w3m)
  --leave-nailed                  Leave the nailed Cargo.toml in place
  -E | --edits-sources            Allow source edits (repeat: file creation)
  -f | --force                    Override some warnings
  --linkfarm[=no|shallow|git|full]        (default varies, usually "no")
  --[no-]git                      Instead of linkfarming, use git
  --just-linkfarm | --clean-linkfarm | --keep-linkfarm (default is keep)
  --just-git                      Implies --git, only does the update
  --[no-]preclean[=no|src|full]               (default is no)
  --just-run                      Run the command, don't do cargo/git stuff
  --subdir=DIR                    Relative cd, right at the beginning
  --chdir=DIR                     Relative cd, just before running command
  --no-nail                       Do not nail, just run the command.
  --no-cargo-lock-manip           Do not manipulate Cargo.lock.
  --no-concurrency-lock           Do not take the concurrency lock.

  -s<subcommand>                  Treat command as `cargo <subcommand>`
  --subcommand-props=<prop>,...   Override command props (see docs)

END

our $self;

use strict;
use POSIX;
use Types::Serialiser;
use File::Glob qw(bsd_glob GLOB_ERR GLOB_BRACE GLOB_NOMAGIC);
use Cwd qw(realpath);

our $base_path;
our %archmap = (
    RPI => 'arm-unknown-linux-gnueabihf',
    WASM => 'wasm32-unknown-unknown',
);

BEGIN {
  $self = $0;  $self =~ s{^.*/(?=.)}{};
  my $deref = $0;
  our $base_path;
  while ($deref =~ m{^/}) {
    my $link = readlink $deref;
    if (!defined $link) {
      $! == EINVAL
	or die "$self: checking our script location $deref: $!\n";
      $deref =~ s{/[^/]+$}{}
	or die "$self: unexpected script path: $deref\n";
      $base_path = $deref;
      unshift @INC, $deref."/TOML-Tiny/lib";
      last;
    }
    last if $link !~ m{^/};
    $deref = $link;
  }
}

use Fcntl qw(LOCK_EX);
use File::Compare;
use TOML::Tiny::Faithful;

our ($src_absdir, $worksphere, $subdir);
our $lockfile = "../.nailing-cargo.lock";
our $nailfile = "../Cargo.nail";

our @args_preface;
our $arg_toolchain;
our $cargo_subcmd;
our $command_is_cargo;
our $alt_cargo_lock;
our $cargo_lock_update;
our $pass_options;
our $online;
our $just_linkfarm;
our $edits_sources=0;
our $leave_nailed;
our $oot_clean;
our $oot_preclean;
our $do_nail=1;
our $do_cargo_lock=1;
our $do_lock=1;
our $linkfarm_depth; # ignored if $gitxfer
our $chdir=undef;
our $clisubdir='';
our $gitxfer; # --git (not the same as --linkfarm=git, see docs)

#
our %subcmd_props = (
# build (default)  =>[qw(                                                )],
 audit             =>[qw( !locked                       linkfarm-shallow )],
 fetch             =>[qw(                     online   !target-dir       )],
 fmt               =>[qw( !locked     !target !offline !target-dir edits )],
'generate-lockfile'=>[qw( lock-update !target          !target-dir       )],
 init              =>[qw(                                        creates )],
 metadata          =>[qw(                              !target-dir       )],
 miri              =>[qw( !locked             !offline  linkfarm-shallow )],
 publish           =>[qw(                     !offline  pristine-git     )],
 update            =>[qw( lock-update !target online                     )],
 upgrades          =>[qw( !locked                      !target-dir       )],
		    );

our @subcmd_xprops = qw(!manifest-path);

our @configs;
our $verbose=1;
our $force=0;
our $forced=0;
our ($noact,$dump);
our $target;

sub print_usage () {
  print $usage or die $!;
  exit 0;
}

sub show_manual () {
  my $manual = ($base_path // '.').'/README.md';
  stat $manual or die "$self: manual not found at $manual: $!\n";;
  exec 'sh','-ec', 'pandoc -- "$1" 2>&1 | w3m -T text/html', '--', $manual;
  die "$self: exec sh failed: $!";
}

sub forceable_warning ($) {
  my ($m) = @_;
  print STDERR "$self: *WARNING*: $m\n";
  if ($force) {
    print STDERR "$self: continuing because of --force...\n" unless $forced++;
    return;
  } else {
    die "$self: Stopping due to warning (override with -f | --force)\n";
  }
}

sub shell_quotify (@) {
  return join ' ', map {
    if (m/\W/) {
      s/\'/\'\\'\'/g;
      $_ = "'$_'";
    }
    $_
  } @_;
}

sub read_or_enoent ($) {
  my ($fn) = @_;
  if (!open R, '<', $fn) {
    return undef if $!==ENOENT;
    die "$self: open $fn: $!\n";
  }
  local ($/) = undef;
  my ($r) = <R> // die "$self: read $fn: $!\n";
  $r;
}

sub stat_exists ($$) {
  my ($fn, $what) = @_;
  if (stat $fn) { return 1; }
  $!==ENOENT or die "$self: stat $what: $fn: $!\n";
  return 0;
}

sub subcmd_p ($) {
  print STDERR " subcmd_p ".(join ' ', keys %$cargo_subcmd)."   | @_\n"
    if $dump;
  $cargo_subcmd->{$_[0]}
}

sub toml_or_enoent ($$) {
  my ($f,$what) = @_;
  my $toml = read_or_enoent($f) // return;
  print STDERR "Read TOML from $f\n" if $dump;
  my ($v,$e) = from_toml($toml);
  if (!defined $v) {
    chomp $e;
    die "$self: parse TOML: $what: $f: $e\n";
  }
  die "$e ?" if length $e;
  $v;
}

sub load1config ($) {
  my ($f) = @_;
  my $toml = toml_or_enoent($f, "config file");
  push @configs, $toml if defined $toml;
}

sub loadconfigs () {
  my $dotfile = ".nailing-cargo.toml";
  load1config("../Nailing-Cargo.toml");
  load1config($dotfile);
  load1config("$ENV{HOME}/$dotfile") if defined $ENV{HOME};
  load1config("/etc/nailing-cargo/cfg.toml");
}

sub unlink_or_enoent ($) { unlink $_[0] or $!==ENOENT; }

sub same_file ($$) {
  my ($x,$y) = @_;
  "@$x[0..5]" eq "@$y[0..5]";
}

sub takelock () {
  return unless $do_lock;

  for (;;) {
    open LOCK, ">", $lockfile or die "$self: open/create $lockfile: $!\n";
    flock LOCK, LOCK_EX or die "$self: lock $lockfile: $!\n";
    my @fstat = stat LOCK or die "$self: fstat: $!\n";
    my @stat  = stat $lockfile;
    if (!@stat) {
      next if $! == ENOENT;
      die "$self: stat $lockfile: $!\n";
    }
    last if same_file(\@fstat,\@stat);
  }
}
sub unlock () {
  unlink $lockfile or die "$self: removing lockfile: $!\n";
}

our $nail;

sub badcfg {
  my $m = pop @_;
  $" = '.';
  die "$self: config key \`@_': $m\n";
}

sub cfg_uc {
  foreach my $cfg (@configs) {
    my $v = $cfg;
    foreach my $k (@_) {
      last unless defined $v;
      ref($v) eq 'HASH' or badcfg @_, "parent key \`$k' is not a hash";
      $v = $v->{$k};
    }
    return $v if defined $v;
  }
  return undef;
}

sub cfge {
  my $exp = shift @_;
  my $v = cfg_uc @_;
  my $got = ref($v) || 'scalar';
  return $v if !defined($v) || $got eq $exp;
  badcfg @_, "found \L$got\E, expected \L$exp\E";
  # ^ toml doesn't make refs to scalars, so this is unambiguous
}

sub cfgn {
  my $exp = shift @_;
  (cfge $exp, @_) // badcfg @_, "missing";
}

sub cfgs  { cfge 'scalar', @_ }
sub cfgsn { cfgn 'scalar', @_ }

sub cfg_bool {
  my $v = cfg_uc @_;
  return $v if !defined($v) || Types::Serialiser::is_bool $v;
  badcfg @_, "expected boolean";
}

sub cfgn_list {
  my $l = cfge 'ARRAY', @_;
  foreach my $x (@$l) {
    !ref $x or badcfg @_, "list contains non-scalar element";
  }
  @$l
}

sub readnail () {
  if (open N, '<', $nailfile) {
    local ($/) = undef;
    my $toml = <N> // die "$self: read $nailfile: $!";
    my $transformed;
    if ($toml !~ m{^\s*\[/}m &&
        $toml !~ m{^[^\n\#]*\=}m &&
        # old non-toml syntax
        $toml =~ s{^[ \t]*([-_0-9a-z]+)[ \t]+(\S+)[ \t]*$}{$1 = \"$2\"}mig) {
      $toml =~ s{^}{[packages\]\n};
      my @sd;
      $toml =~ s{^[ \t]*\-[ \t]*\=[ \t]*(\"[-_0-9a-z]+\"\n?)$}{
        push @sd, $1; '';
      }mige;
      $toml = "subdirs = [\n".(join '', map { "$_\n" } @sd)."]\n".$toml;
      $transformed = 1;
    }
    my $e;
    ($nail,$e) = from_toml($toml);
    if (!defined $nail) {
      if ($transformed) {
        $toml =~ s/^/    /mg;
        print STDERR "$self: $nailfile transformed into TOML:\n$toml\n";
      }
    $/="\n"; chomp $e;
      die "$self: parse $nailfile: $e\n";
    }
    die "$e ?" if length $e;
  } elsif ($! != ENOENT) {
    die "$self: open $nailfile: $!\n";
  }

  $nail->{subdirs} //= [ ];

  if (!ref $nail->{subdirs}) {
    $nail->{subdirs} = [
      grep /^[^\#]/,
      map { s/^\s+//; s/\s+$//; $_; }
      split m{\n},
      $nail->{subdirs}
    ];
  }

  unshift @configs, $nail;
}

sub get_dependency_tables ($) {
  my ($toml) = @_;
  my @keys = qw(dependencies build-dependencies dev-dependencies);
  my @r;
  my $process = sub {
    my ($node) = @_;
    foreach my $k (@keys) {
      my $deps = $node->{$k};
      push @r, $deps if $deps;
    }
  };
  $process->($toml);
  foreach my $target_node (values %{ $toml->{target} // { } }) {
    $process->($target_node);
  }
  @r;
}

our @alt_cargo_lock_stat;

sub consider_alt_cargo_lock () {
  my @ck = qw(alt_cargo_lock);
  # User should *either* have Cargo.lock in .gitignore,
  # or expect to commit Cargo.lock.example ($alt_cargo_lock)

  return unless $do_cargo_lock;

  $alt_cargo_lock = (cfg_uc @ck);

  my $force = 0;
  if (defined($alt_cargo_lock) && ref($alt_cargo_lock) eq 'HASH') {
    $force = cfg_bool qw(alt_cargo_lock force);
    my @ck = qw(alt_cargo_lock file);
    $alt_cargo_lock = cfg_uc @ck;
  }
  $alt_cargo_lock //= Types::Serialiser::true;

  if (Types::Serialiser::is_bool $alt_cargo_lock) {
    if (!$alt_cargo_lock) { $alt_cargo_lock = undef; return; }
    $alt_cargo_lock = 'Cargo.lock.example';
  }

  if (ref($alt_cargo_lock) || $alt_cargo_lock =~ m{/}) {
    badcfg @ck, "expected boolean, or leafname";
  }

  my $check = $alt_cargo_lock;
  $check = "$chdir/$check" if length $chdir;
  if (!stat_exists $check, "alt_cargo_lock") {
    $alt_cargo_lock = undef unless $force;
    return;
  }
  
  @alt_cargo_lock_stat = stat _;
}

our $oot_dir;      # oot.dir or "Build"
our $oot_absdir;

sub consider_oot () {
  $oot_dir = cfgs qw(oot dir);
  my $use = cfgs qw(oot use);
  unless (defined($oot_dir) || defined($use) ||
	  defined(cfg_uc qw(oot user))) {
    return;
  }
  if (($use//'') eq 'disable') {
    $oot_dir = undef;
    return;
  }

  # OOT
  $oot_clean //= cfg_bool qw(oot clean);
  $oot_dir //= 'Build';
  $oot_absdir = ($oot_dir !~ m{^/} ? "$worksphere/" : ""). $oot_dir;

  if (subcmd_p('pristine-git')) {
    $gitxfer = 1 if stat_exists('.git', 'source .git directory');
    $oot_preclean //= 'full';
  }
}

our %manifests;
our %packagemap;
our %workspaces;
our @queued_paths;

sub read_manifest ($$$) {
  my ($subdir, $org_subdir, $why) = @_;
  my $manifest = "../$subdir/Cargo.toml";
  print STDERR "$self: reading $manifest...\n" if $verbose>=4;
  if (defined $manifests{$manifest}) {
    print STDERR
 "$self: warning: $subdir: specified more than once!".
 " (ignoring $why)\n";
    return undef;
  }
  foreach my $try ("$manifest.unnailed", "$manifest") {
    my $toml = toml_or_enoent($try, "manifest, in $why") // next;
    my $ws = $toml->{workspace};
    if ($ws) {
      queue_workspace_members($subdir, $org_subdir, $ws, "$subdir, $why");
    }
    my $p = $toml->{package}{name};
    if (!defined $p and !defined $ws) {
      print STDERR
 "$self: warning: $subdir, $why: missing package.name in $try, ignoring\n";
      next;
    }
    $manifests{$manifest} = [ $toml, $org_subdir ] if $p;
    foreach my $dep (get_dependency_tables $toml) {
      next unless defined $dep->{path};
      queue_referenced_path($dep->{path}, $org_subdir,
			    "dependency of $subdir, $why");
    }
    return ($p, $ws);
  }
  return undef;
}

sub queue_workspace_members ($$) {
  my ($subdir, $org_subdir, $ws_toml, $what) = @_;
  # We need to (more or less) reimplement the cargo workspace
  # membership algorithm (see the "workspaces" section of the cargo
  # reference).  How tiresome.
  #
  # It's not quite the same for us because we aren't interested in
  # whether cargo thinks things are "in the workspace".  But we do
  # need to do the automatic discover.

  my @include = @{ $ws_toml->{members} // [ ] };
  my $exclude = $ws_toml->{exclude} // [ ];

  my @exclude = map {
    s/[^*?0-9a-zA-Z_]/\\$&/g;
    s/\?/./g;
    s/\*/.*/g;
  } @$exclude;

  foreach my $spec (@include) {
    if ($spec =~ m{^/}) {
      print STDERR
	"$self: warning: absolute workspace member $spec in $what (not nailing, but cargo will probably use it)\n";
      next;
    }
    my $spec_glob_prefix = "../$subdir/";
    my $spec_glob = "$spec_glob_prefix$spec";
    my $globflags = GLOB_ERR|GLOB_BRACE|GLOB_NOMAGIC;
    foreach my $globent (bsd_glob($spec_glob, $globflags)) {
      my $ent_prefix = substr($globent, 0, length $spec_glob_prefix);
      if ($ent_prefix ne $spec_glob_prefix) {
	print STDERR
      "$self: warning: $globent ($spec_glob, $what) points outside $spec_glob_prefix, not following so not nailing (although cargo probably will follow it)\n";
	next;
      }
      next if grep { $globent =~ m{^$_$} } @exclude;
      queue_referenced_path($globent, $org_subdir,
			    "member of workspace $what");
    }
  }
}

sub queue_referenced_path ($$$) {
  my ($spec_path, $org_subdir, $why) = @_;
  open REALPATH, "-|",
    qw(realpath), "--relative-to=../$org_subdir", "--", $spec_path
    or die "$self: fork/pipe/exec for realpath(1)\n";
  my $rel_path = do { local $/=undef; <REALPATH>; };
  $?=0; $!=0;
  my $r = close(REALPATH);
  die "$self: reap realpath: $!\n" if $!;
  if (!chomp($rel_path) or $?) {
    print STDERR
 "$self: warning: failed to determine realpath for $spec_path in $org_subdir (exit code $?)\n";
    return;
  }

  my $q_subdir = "$org_subdir/$rel_path";
  print STDERR "$self: making a note to look at $q_subdir, $why)\n"
    if $verbose >= 4;

  push @queued_paths, [ "$q_subdir", $org_subdir, $why ];
}

sub readorigs () {
  # We (and our callees) populate %packagemap and %manifest, so if we
  # don't run, they remain empty and nothing is nailed.
  return unless $do_nail;

  foreach my $p (keys %{ $nail->{packages} }) {
    my $v = $nail->{packages}{$p};
    my $subdir = ref($v) ? $v->{subdir} : $v;
    my ($gotpackage, $ws) = read_manifest($subdir, $subdir, "from [packages]");
    $gotpackage //= '<nothing!>';
    if ($gotpackage ne $p) {
      print STDERR
 "$self: warning: honouring Cargo.nail packages.$subdir=$p even though $subdir contains package $gotpackage!\n";
    }
    die if defined $packagemap{$p};
    $packagemap{$p} = [ $subdir, $subdir ];
  }
  foreach my $subdir (@{ $nail->{subdirs} }) {
    my ($gotpackage,$ws) = read_manifest($subdir, $subdir, "from [subdirs]");
    if (!defined $gotpackage) {
      print STDERR
 "$self: warning: ignoring subdir $subdir which has no (suitable) Cargo.toml\n"
        unless $ws;
      next;
    }
    $packagemap{$gotpackage} //= [ $subdir, $subdir ];
  }
  while (my ($subdir, $org_subdir, $why) = @{ shift @queued_paths or [] }) {
    $subdir =~ s{/\.$}{};
    next if $manifests{"../$subdir/Cargo.toml"};
    my ($gotpackage, $ws) = read_manifest($subdir, $org_subdir, $why);
    next unless $gotpackage;
    $packagemap{$gotpackage} //= [ $subdir, $org_subdir ];
  }
}

sub calculate () {
  foreach my $p (sort keys %packagemap) {
    print STDERR "$self: package $p in $packagemap{$p}[0]\n" if $verbose>=2;
  }
  foreach my $mf (keys %manifests) {
    die "internal error" unless $do_nail; # belt and braces

    my ($toml, $mf_org_subdir) = @{ $manifests{$mf} };
    foreach my $deps (get_dependency_tables $toml) {
      next unless $deps;
      foreach my $dep_key (keys %$deps) {
	my $info = $deps->{$dep_key};
	my $p = (ref $info ? $info->{package} : undef) // $dep_key;
	next unless defined $packagemap{$p};
	next if $packagemap{$p}[1] eq $mf_org_subdir;
	$deps->{$dep_key} = $info = { } unless ref $info; # was just version
	my $oldpath = $info->{path};
	delete $info->{version};
	my $newpath = $worksphere.'/'.$packagemap{$p}[0];
	print STDERR "in $mf set $p path=$newpath (was ".
	  ($oldpath // '<unset>').")\n"
	  if $verbose >= 4;
	$info->{path} = $newpath;
	delete $info->{git};
	delete $info->{branch};
      }
    }
    my $nailing = "$mf.nailing~";
    unlink_or_enoent $nailing or die "$self: remove old $nailing: $!\n";
    open N, '>', $nailing or die "$self: create new $nailing: $!\n";
    print N to_toml($toml) or die "$self: write new $nailing: $!\n";
    close N or die "$self: close new $nailing: $!\n";
  }
}

sub addargs () {
  # TODO $gitxfer support!
  if ($edits_sources==1) {
    $linkfarm_depth = 'copy-edit';
  } elsif ($edits_sources>=2) {
    $linkfarm_depth = 'copy-edit-all';
  }

  if ($just_linkfarm) {
    die "$self: --just-linkfarm but not doing out-of-tree builds!\n"
      unless defined $oot_dir;
    @ARGV = ();
    return;
  }

  if (!defined $online) {
    $_ = cfg_uc qw(misc online);
    if (!defined $_) {
    } elsif (Types::Serialiser::is_bool $_) {
      $online = $_;
    } elsif (ref $_) {
    } elsif (m/^a/) {
      $online = undef;
    } elsif (m/^[1ty]/) { # allow booleanish strings
      $online = 1;        # for less user frustration
    } elsif (m/^[0fn]/) {
      $online = 0;
    } else {
      badcfg qw(misc online), "expected boolean or 'auto', found '$_'";
    }
  }
  $online //= 1 if subcmd_p('online');
  $online //= 0;

  if ($edits_sources>=2) {
    $oot_preclean //= 'src';
    if ($oot_preclean !~ m/^(?:src|full)$/) {
      forceable_warning
 "-EE specified, but also --preclean=no; will probably leave your source tree full of junk";
    }
  }

  if (subcmd_p('linkfarm-gitclean')) {
    $linkfarm_depth //= 'git';
    $oot_preclean //= 'src';
  }

  $cargo_lock_update //= subcmd_p('lock-update');
  $linkfarm_depth //=
    subcmd_p('pristine-git')     ? 'git'     :
    subcmd_p('linkfarm-shallow') ? 'shallow' :
    $cargo_lock_update           ? 'shallow' :
    '';

  $oot_preclean //= $gitxfer ? 'src' : 'no';

  my $toolchain = cfgs qw(misc usual_toolchain);
  $toolchain =~ s{^\+}{} if defined $toolchain;
  @args_preface = map {
    $_ ne "\0+"        ? $_            :
    defined $toolchain ? "+$toolchain" :
    ()
  } @args_preface;
  print STDERR "toolchain ".($toolchain // '<undef>')." \n" if $dump;
  if (defined $toolchain) {
    $ENV{NAILINGCARGO_TOOLCHAIN} = "+$toolchain";
  } elsif (defined $arg_toolchain) {
    $ENV{NAILINGCARGO_TOOLCHAIN} = $arg_toolchain;
  }

  our @add;

  if (!$cargo_lock_update) {
    push @add, qw(--locked) unless subcmd_p('!locked');
  }
  if ($linkfarm_depth eq '' && !$gitxfer) {
    if (defined($oot_dir) && !subcmd_p('!manifest-path')) {
      my $cargotoml = "${src_absdir}/Cargo.toml";
      push @args_preface, "--manifest-path=$cargotoml" if $pass_options;
      push @add, qw(--target-dir=target) unless subcmd_p('!target-dir');
    }
  }

  if (defined($target) && !subcmd_p('!target')) {
    if ($target =~ m{^[A-Z]}) {
      $target = (cfgs 'arch', $target) // $archmap{$target}
	// die "$self: --target=$target alias specified; not in cfg or map\n";
    }
    push @add, "--target=$target";
  }

  push @add, "--offline" unless $online || subcmd_p('!offline');

  if (subcmd_p('creates') && $edits_sources < 2) {
    forceable_warning
 "this subcommand expects to create new source files; you probably want to specify --edits-sources twice aka -EE (which is not the default even now, for safety reasons)";
  } elsif (subcmd_p('edits') && !$edits_sources) {
    forceable_warning
 "this subcommand expects to edit the source code; you probably want to specify --edits-sources aka -E (which is not the default even now, for safety reasons)";
  }

  push @args_preface, @add if $pass_options;
  die if grep { m/ / } @add;
  $ENV{NAILINGCARGO_CARGO_OPTIONS} = "@add";

  unshift @ARGV, @args_preface;
}

our $build_absdir; # .../Build/<subdir>

sub oot_massage_cmdline () {
  return unless defined $oot_dir;

  my $use = cfgs qw(oot use);
  $use // die "$self: out-of-tree build, but \`oot.use' not configured\n";
  $build_absdir = "$oot_absdir/$subdir";

  my ($pre,$post) = ('','');
  my @xargs;
  $pre .= "set -x;" if $dump;

  my $std_pre = sub {
    push @xargs, $oot_absdir, $subdir, $src_absdir;
    $pre .= <<'END_BOTH';
        bld="$1"; shift; sd="$1"; shift; src="$1"; shift;  
        cd "$bld"; mkdir -p -- "$sd"; cd "$sd";
END_BOTH
  };

  if ($gitxfer) {
    $std_pre->();
    $pre .= <<'END_GIT_XFER_PREP';
      if test -d .git; then :; else
	  git init;
      fi;
      mkdir -p .git/nailing-cargo .git/logs/refs/nailing-cargo;
      >>.git/logs/refs/nailing-cargo/src;
      parent_exists=$(set -e; cd "$src/"; git rev-parse --verify -q HEAD~0 || test $? = 1);
      if [ "$parent_exists" ]; then
        git fetch "$src" +HEAD:refs/nailing-cargo/src;
      fi;
      branch_exists=$(git rev-parse --verify -q HEAD~0 || test $? = 1);
      if [ "$branch_exists" ]; then git checkout --quiet --detach; fi;
END_GIT_XFER_PREP

    if ($oot_preclean ne 'no') {
      $pre.= "git clean -xdf".
	( $oot_preclean =~ /full/ ? ''
	  : ' -e/target'.
	  ( $clisubdir ne ''
	    ? " -e/".(shell_quotify "$clisubdir")."target"
	    : '' )
	).
	';';
    }
    $pre.= "git reset -q --hard;";

    $pre .= <<'END_GIT_XFER_MKTREE';
      if [ "$parent_exists" ]; then
        git checkout --quiet refs/nailing-cargo/src~0 --;
      fi;
      cp .git/index .git/nailing-cargo/index;
      exec 3>&1;
      exec >.git/nailing-cargo/commit;
      printf 'tree ';
      (set -e; cd "$src";
       GIT_DIR="$bld/$sd"/.git;
       GIT_INDEX_FILE="$GIT_DIR/nailing-cargo/index";
       export GIT_DIR GIT_INDEX_FILE;
       git add . >&2;
       if test -f Cargo.lock; then git add -f Cargo.lock >&2; fi;
       git write-tree);

      read <.git/nailing-cargo/commit our_tree;
      if [ "$parent_exists" ]; then
        their_tree=$(git cat-file commit refs/nailing-cargo/src | sed 1q);
      fi;
      if [ "x$our_tree" = "x$their_tree" ]; then
        git checkout --quiet refs/nailing-cargo/src --;
      else
END_GIT_XFER_MKTREE
    if (subcmd_p('pristine-git')) {
      $pre .= <<'END_GIT_XFER_CLEAN';
        echo >&2 '*** original source working tree is dirty - refusing! ***';
        exit 12;    
END_GIT_XFER_CLEAN
    } else {
      $pre .= <<'END_GIT_XFER_DIRTY';
        if [ "$parent_exists" ]; then
          printf 'parent ';
          git rev-parse HEAD~0;
        fi;
        authline=$(date +'nailing-cargo <nailing-cargo@invalid> %s %z');
        printf "author %s\ncommitter %s\n\nnailing-cargo autocommit dirty working tree\n" "$authline" "$authline";
        obj=$(git hash-object -t commit -w .git/nailing-cargo/commit);
        exec >&2;
        git checkout --quiet "$obj";
END_GIT_XFER_DIRTY
    }
    $pre .= <<'END_GIT_XFER';
      fi;
      exec >&3;
END_GIT_XFER
    if ($edits_sources) {
      $pre .= <<'END_GIT_XFER_EDITS_CLEANUP';
git update-ref refs/nailing-cargo/edited HEAD~0:;
END_GIT_XFER_EDITS_CLEANUP
      $post .= ':;'; # forces us to not use exec
      $pre .= <<'END_GIT_XFER_EDITS_CAPTURE';
        trap '
          rc=$?;
          git add -A .;
          tree=$(git write-tree);
          git update-ref refs/nailing-cargo/edited $tree;
          exit $rc;
        ' 0;
END_GIT_XFER_EDITS_CAPTURE
    }
  } elsif ($linkfarm_depth eq '') {
    push @xargs, $build_absdir;
    $pre .= 'cd "$1"; shift; ';
    $post .= '';
  } else { # not $gitxfer, some $linkfarm_depth
    $std_pre->();
    if ($oot_preclean ne 'no') {
      $pre.= "find . -maxdepth 1 ! -path .";
      $pre.= " ! -path ./target" if $oot_preclean ne 'full';
      $pre.= " -print0 | xargs -0r rm -r --;"
    }
    if ($linkfarm_depth eq 'shallow') {
      $pre.= <<'END_SHALLOW';
	clean () { find -lname "$src/*" -print0 | xargs -0r rm --; }; clean;
	find "$src" -maxdepth 1 \! -name Cargo.lock -print0 |
	xargs -0r sh -ec 'for f in "$@"; do
		rm -rf -- "${f##*/}";
		ln -sf -- "$f" .;
	done';
END_SHALLOW
    } elsif ($linkfarm_depth =~ /full|git/) {
      $pre .= <<'END_EITHER_DEEP_DIRS';
	clean () { find -follow -lname "$src/*" -print0 | xargs -0r rm --; };
	(set -e; cd "$src"; find . \! -name Cargo.lock \! \( -name .git -prune \) \! -path . \! -name .git -type d -print0) |
	xargs -0r sh -ec 'for f in "$@"; do
		rm -f -- "$f" 2>/dev/null ||:;
		mkdir -p "$f";
	done' x;
END_EITHER_DEEP_DIRS
      if ($linkfarm_depth eq 'git') {
	$pre .= <<'END_FILES_GIT'
        (set -e; cd "$src"; git ls-files --exclude-standard -co -z) |
END_FILES_GIT
      } elsif ($linkfarm_depth eq 'full') {
	$pre .= <<'END_FILES_FULL'
	(set -e; cd "$src"; find . \! -name Cargo.lock \! \( -name .git -prune \) \! -type d -print0) |
END_FILES_FULL
      }
      $pre .= <<'END_DEEP';
	perl -0 -ne '
		BEGIN { $src=shift @ARGV; }
		next if (readlink "$_"//"") eq "$src/$_";
		unlink "$_";
		symlink "$src/$_", "$_" or die "$_ $!";
	' "$src";
END_DEEP
    } elsif ($linkfarm_depth =~ m/^copy-edit/) {
      $pre .= <<'END_COPY_EDIT_PRE';
	find -lname "$src/*" -print0 | xargs -0r rm --;
        (set -e; cd "$src"; git ls-files -c -z |
        cpio --quiet -p0m --no-preserve-owner -u --make-directories "$bld/$sd");
END_COPY_EDIT_PRE
    } else {
       die "$linkfarm_depth ?";
    }
    if ($linkfarm_depth =~ m/^copy-edit/) {
      $pre .= <<'END_COPY_EDIT';
	clean () {
          (set -e; cd "$src"; git ls-files -c -z) | xargs -0r rm -df --;
        };
END_COPY_EDIT
      if ($linkfarm_depth eq 'copy-edit-all') {
        $post .= <<'END_COPY_EDIT_GENFILES_ALL';
        find -xdev \( \( -name .git -o -path ./target -o -path ./nailing-cargo-update.tar \) -prune \) -o
              \( -type l -o -type f \) -print0 |
END_COPY_EDIT_GENFILES_ALL
      } else {
        $post .= <<'END_COPY_EDIT_GENFILES_GIT';
        (set -e; cd "$src"; git ls-files -c -z) |
END_COPY_EDIT_GENFILES_GIT
      }
      $post .= <<'END_COPY_EDIT_BUNDLE';
        cpio -Hustar -o0 --quiet >"nailing-cargo-update.tar";
END_COPY_EDIT_BUNDLE
    $pre .= <<'ENDLK' if $do_cargo_lock;
	if test -e Cargo.lock || test -e "$src"/Cargo.lock; then
	  rm -f Cargo.lock;
          cp -- "$src"/Cargo.lock .;
        fi;
ENDLK
    } # endif copy-edit
    $post .= <<'ENDCLEAN' if $oot_clean && !$just_linkfarm;
        clean;
ENDCLEAN
  }
  my $addpath = (cfg_uc qw(oot path_add)) //
    $use eq 'really' || $use eq 'sudo'
    ? Types::Serialiser::true : Types::Serialiser::false;
  $addpath =
    !Types::Serialiser::is_bool $addpath ? $addpath           :
    $addpath                             ? '$HOME/.cargo/bin' :
                                           undef;
  if (defined $addpath) {
    $pre .= <<END
        PATH=$addpath:\${PATH-/usr/local/bin:/bin:/usr/bin};
        export PATH;
END
  } # endif not $gitxfer, some $linkfarm_depth
  $pre .= <<END unless $online;
        CARGO_NET_OFFLINE=true; RUSTUP_AUTO_INSTALL=0;
        export CARGO_NET_OFFLINE RUSTUP_AUTO_INSTALL;
END
  $pre  =~ s/^\s+//mg; $pre  =~ s/\s+/ /g;
  $post =~ s/^\s+//mg; $post =~ s/\s+/ /g;

  my $getuser = sub { cfgsn qw(oot user) };
  my @command;
  my $xe = $verbose >= 2 ? 'xe' : 'e';
  my $sh_ec = sub {
    if (!length $post) {
      @command = (@_, 'sh',"-${xe}c",$pre.'exec "$@"','--',@xargs);
    } else {
      @command = (@_, 'sh',"-${xe}c",$pre.'"$@"; '.$post,'--',@xargs);
    }
    my $eff_chdir = "$clisubdir$chdir";
    if (length $eff_chdir) {
      push @command, "env", "--chdir=$eff_chdir", "--";
    }
    push @command, @ARGV;
  };
  my $command_sh = sub {
    my $quoted = shell_quotify @ARGV;
    my $qargs = shell_quotify @xargs;
    @command = (@_, "set -${xe}; set -- $qargs; $pre $quoted; $post");
  };
  if ($verbose) {
    if ($gitxfer) {
      print STDERR "$self: out-of-tree, git, building in: \`$build_absdir'\n";
    } else {
      print STDERR "$self: out-of-tree, raw, building in: \`$build_absdir'\n";
    }
  }
  if ($use eq 'really') {
    my $user = $getuser->();
    my @pw = getpwnam $user or die "$self: oot.user \`$user' lookup failed\n";
    my $homedir = $pw[7];
    $sh_ec->('really','-u',$user,'env',"HOME=$homedir");
    print STDERR "$self: using really to run as user \`$user'\n" if $verbose;
  } elsif ($use eq 'sudo') {
    my $user = $getuser->();
    $sh_ec->(qw(sudo -u), $user);
    print STDERR "$self: using sudo to run as user \`$user'\n" if $verbose;
  } elsif ($use eq 'ssh') {
    my $user = $getuser->();
    $user .= '@localhost' unless $user =~ m/\@/;
    $command_sh->('ssh',$user);
    print STDERR "$self: using ssh to run as \`$user'\n" if $verbose;
  } elsif ($use eq 'command_args') {
    my @c = cfgn_list qw(oot command);
    $sh_ec->(@c);
    print STDERR "$self: out-of-tree, adverbial command: @c\n" if $verbose;
  } elsif ($use eq 'command_sh') {
    my @c = cfgn_list qw(oot command);
    $command_sh->(@c);
    print STDERR "$self: out-of-tree, ssh'ish command: @c\n" if $verbose;
  } elsif ($use eq 'null') {
    $sh_ec->();
  } else {
    die "$self: oot.use mode $use not recognised\n";
  }
  die unless @command;
  @ARGV = @command;
}

sub setenvs () {
  $ENV{CARGO_MANIFEST_DIR} = $src_absdir.$clisubdir unless !$gitxfer && $linkfarm_depth;
  $ENV{NAILINGCARGO_MANIFEST_DIR} = $src_absdir.$clisubdir;
  $ENV{NAILINGCARGO_WORKSPHERE}   = $worksphere;
  $ENV{NAILINGCARGO_BUILDSPHERE}  = $oot_absdir;
  delete $ENV{NAILINGCARGO_BUILDSPHERE} unless $oot_absdir;
  $ENV{NAILINGCARGO_BUILD_DIR}    = ($build_absdir // $src_absdir).$clisubdir;
}

our $want_uninstall;

END {
  if ($want_uninstall) {
    local ($?);
    foreach my $mf (keys %manifests) {
      eval { uninstall1($mf,1); 1; } or warn "$@";
    }
    eval { unaltcargolock(1); 1; } or warn "$@";
  }
}

sub consider_directories () {
  return unless defined $oot_dir;
  my $bsubdir = "../$oot_dir/$subdir";
  return if stat $bsubdir;
  die "$0: build directory $bsubdir inaccessible\n"
    unless $!==ENOENT;
}

our $cleanup_cargo_lock;
sub makebackups () {
  foreach my $mf (keys %manifests) {
    link "$mf", "$mf.unnailed" or $!==EEXIST
      or die "$self: make backup link $mf.unnailed: $!\n";
  }

  if (defined($alt_cargo_lock)) {
    die 'internal error' unless $do_cargo_lock;
    if (@alt_cargo_lock_stat) {
      print STDERR "$self: using alt_cargo_lock `$alt_cargo_lock'..."
	if $verbose>=3;
      if (link $alt_cargo_lock, 'Cargo.lock') {
	print STDERR " linked\n" if $verbose>=3;
      } elsif ($! != EEXIST) {
	print STDERR "\n" if $verbose>=3;
	die "$self: make \`Cargo.lock' available as \`$alt_cargo_lock': $!\n";
      } else {
	print STDERR "checking quality." if $verbose>=3;
	my @lock_stat = stat 'Cargo.lock'
	  or die "$self: stat Cargo.lock (for alt check: $!\n";
	same_file(\@alt_cargo_lock_stat, \@lock_stat)
	  or die
"$self: \`Cargo.lock' and alt file \`$alt_cargo_lock' both exist and are not the same file!\n";
      }
      $cleanup_cargo_lock = 1;
    } else {
      $cleanup_cargo_lock = 1;
      # If Cargo.lock exists and alt doesn't, that means either
      # that a previous run was interrupted, or that the user has
      # messed up.
    }
  }
}

sub nailed ($) {
  my ($mf) = @_;
  my $nailed  = "$mf.nailed~"; $nailed =~ s{/([^/]+)$}{/.$1} or die;
  $nailed;
}    

sub install () {
  my @our_unfound_stab = stat_exists('Cargo.toml', 'local Cargo.toml')
    ? (stat _) : ();
  foreach my $mf (keys %manifests) {
    if (@our_unfound_stab) {
      if (stat_exists $mf, "manifest in to-be-nailed directory") {
	my @mf_stab = stat _ ;
	if ("@mf_stab[0..1]" eq "@our_unfound_stab[0..1]") {
	  @our_unfound_stab = ();
	}
      }
    }

    my $nailing = "$mf.nailing~";
    my $nailed = nailed($mf);
    my ($use, $rm);
    my $diff;
    if (open NN, '<', $nailed) {
      $diff = compare($nailing, \*NN);
      die "$self: compare $nailing and $nailed: $!" if $diff<0;
    } else {
      $!==ENOENT or die "$self: check previous $nailed: $!\n";
      $diff = 1;
    }
    if ($diff) {
      $use = $nailing;
      $rm  = $nailed;
    } else {
      $use = $nailed;
      $rm  = $nailing;
    }
    rename $use, $mf or die "$self: install nailed $use: $!\n";
    unlink_or_enoent $rm or die "$self: remove old $rm: $!\n";
    print STDERR "$self: nailed $mf\n" if $verbose>=3;
  }

  # Warn only if subdirs had something in it.
  if (@our_unfound_stab && %manifests) {
    print STDERR
 "$self: *WARNING* cwd is not in Cargo.nail though it has Cargo.toml!\n";
  }
}

sub invoke () {
  my $r = system @ARGV;
  if (!$r) {
    return 0;
  } elsif ($r<0) {
    print STDERR "$self: could not execute $ARGV[0]: $!\n";
    return 127;
  } elsif ($r & 0xff00) {
    print STDERR "$self: $ARGV[0] failed (exit status $r)\n";
    return $r >> 8;
  } else {
    print STDERR "$self: $ARGV[0] died due to signal! (wait status $r)\n";
    return 125;
  }
}

sub files_return_after_update () {
  return unless defined $oot_dir;

  if ($edits_sources) {
    if ($gitxfer) {
      my $cmd = '';
      $cmd .= "set -x;" if $verbose >= 2;
      $cmd .= ': in source tree;';
      $cmd .= <<'END_GIT_XFER_RETURN';
	  git_dir=$(git rev-parse --git-dir);
	  mkdir -p -- "$git_dir"/nailing-cargo;
          rm -rf "$git_dir"/nailing-cargo/stunt-copy;
          mkdir -- "$git_dir"/nailing-cargo/stunt-copy;
          GIT_DIR="$git_dir"/nailing-cargo/stunt-copy git init;
          mkdir -p -- "$git_dir"/nailing-cargo/stunt-copy/info;
          rm -rf "$git_dir"/nailing-cargo/stunt-copy/objects "$git_dir"/nailing-cargo/stunt-copy/info/refs "$git_dir"/nailing-cargo/stunt-copy/refs;
          ln -s "$1"/.git/objects "$git_dir"/nailing-cargo/stunt-copy/objects;
          ln -s "$1"/.git/refs "$git_dir"/nailing-cargo/stunt-copy/refs;
          ln -s "$1"/.git/info/refs "$git_dir"/nailing-cargo/stunt-copy/info/refs;
	  git fetch -q "$git_dir"/nailing-cargo/stunt-copy +refs/nailing-cargo/edited:refs/nailing-cargo/edited;
	  if test -e "$git_dir"/index; then
            cp -- "$git_dir"/index "$git_dir"/nailing-cargo/index;
          fi;
	  export GIT_INDEX_FILE="$git_dir"/nailing-cargo/index;
END_GIT_XFER_RETURN
      if ($edits_sources >= 2) {
	$cmd .= <<'END_GIT_XFER_CHECKOUT_ALL'
          git checkout refs/nailing-cargo/edited -- .;
END_GIT_XFER_CHECKOUT_ALL
      } else {
	# This horrible rune involving grep and perl is there to exclude
	# submodules, which appear in git ls-files but which can't be fed
	# to git checkout.
	$cmd .= <<'END_GIT_XFER_CHECKOUT_EXISTING'
	  git ls-files -c -z |
          grep -z -v -F -f <(git ls-tree -zr HEAD | perl -0 -ne 'print if s{^\d+ commit \w+\t}{}') |
	  xargs -0r git checkout refs/nailing-cargo/edited --;
END_GIT_XFER_CHECKOUT_EXISTING
      }
      $cmd  =~ s/^\s+//mg; $cmd  =~ s/\s+/ /g;
      if ($dump) {
	eval '
          use Data::Dumper;
          print STDERR Dumper($build_absdir, $cmd);
        ' or die $@;
      }
      system qw(bash -ec), $cmd, 'x', $build_absdir;
    } else {
      my $tar_source_opts;
      my $tar_stdin;
      if ($edits_sources >= 2) {
	$tar_source_opts = '--null --files-from=-';
	$tar_stdin = <<'END_GIT_FILES';
        git ls-files -c -z | \
END_GIT_FILES
      } else {
	$tar_source_opts = '--anchored --exclude=.git --exclude="*/.git" --exclude=target --exclude=nailing-cargo-update.tar';
	$tar_stdin = '';
      }
      system qw(sh -ec), $tar_stdin . <<'END', 'x', "$build_absdir";
	tar -x --keep-newer-files --no-same-permissions --no-same-owner \
	  --no-acls --no-selinux --no-xattrs --warning=no-ignore-newer \
	  -Hustar $tar_source_opts --force-local \
	  -f "$1/nailing-cargo-update.tar"
END
    }
  } elsif ($do_cargo_lock && $cargo_lock_update && !$just_linkfarm) {
    # avoids importing File::Copy and the error handling is about as good
    $!=0; $?=0;
    my $r= system qw(cp --), "$build_absdir/Cargo.lock", "Cargo.lock";
    die "$self: run cp: $! $?" if $r<0 || $r & 0xff;
    die "$self: failed to update local Cargo.lock (wait status $r)\n" if $r;
  }
}

sub uninstall1 ($$) {
  my ($mf, $enoentok) = @_;
  my $unnailed = "$mf.unnailed";
  rename $unnailed, $mf or ($enoentok && $!==ENOENT)
    or die "$self: failed to restore: rename $unnailed back to $mf: $!\n";
}

sub unaltcargolock ($) {
  my ($enoentok) = @_;
  return unless $cleanup_cargo_lock;
  die 'internal error!' unless $do_cargo_lock && defined $alt_cargo_lock;

  # we ignore $enoentok because we don't know if one was supposed to
  # have been created.

  rename('Cargo.lock', $alt_cargo_lock) or $!==ENOENT or die
 "$self: cleanup: rename possibly-updated \`Cargo.lock' to \`$alt_cargo_lock': $!\n";

  unlink 'Cargo.lock' or $!==ENOENT or die
 "$self: cleanup: remove \`Cargo.lock' in favour of \`$alt_cargo_lock': $!\n";
  # ^ this also helps clean up the stupid rename() corner case
}

sub uninstall () {
  foreach my $mf (keys %manifests) {
    my $nailed = nailed($mf);
    link $mf, $nailed or die "$self: preserve (link) $mf as $nailed: $!\n";
    uninstall1($mf,0);
  }
  unaltcargolock(0);
}

sub parse_args () {
  my $is_cargo;

  # Loop exit condition:
  #   $is_cargo is set
  #   @ARGV contains
  #    $is_cargo==1   <cargo-command> <cargo-opts> [--] <subcmd>...
  #    $is_cargo==0   <build-command>...

 OPTS: for (;;) {
    if (!@ARGV) {
      die "$self: need cargo subcommand\n"
	unless $noact || $just_linkfarm;;
      push @ARGV, "CARGO-SUBCOMMAND"; # dummy, user may see it
    }

    $_ = shift @ARGV;
    my $orgopt = $_;

    my $not_a_nailing_opt = sub { # usage 1
      unshift @ARGV, $orgopt;
      if ($orgopt =~ m{^\+}) {
	# We don't have the usual_toolchain here since we haven't
	# read the config yet.  Insert this dummy argument which
	# we'll substitute later.  This can't occur some other way
	# because no-one can pass nuls into arguments.
	$arg_toolchain = $&;
      } else {
	unshift @ARGV, "\0+";
      }
      unshift @ARGV, 'cargo';
      $is_cargo = 1;
      no warnings qw(exiting);
      last OPTS;
    };
    $not_a_nailing_opt->() unless m{^-};
    $not_a_nailing_opt->() if $_ eq '--';

    if ($_ eq '---') { # usage 2 or 3
      if (!@ARGV) {
	die "$self: --- must be followed by build command\n" unless $noact;
	push @ARGV, 'BUILD-COMMAND';
      }
      if ($ARGV[0] eq '--') { # usage 3
	shift @ARGV;
	$is_cargo = 0;
      } elsif (grep { $_ eq '--' } @ARGV) { # usage 2
	$is_cargo = 1;
      } elsif ($ARGV[0] =~ m{[^/]*cargo[^/]*$}) { # usage 2
	$is_cargo = 1;
      } else {	# usage 3
	$is_cargo = 0;
      }
      last;
    }
    if (m{^-[^-]}) {
      while (m{^-.}) {
	if (s{^-h}{-}) {
	  print_usage();
	} elsif (s{^-v}{-}) {
	  $verbose++;
	} elsif (s{^-q}{-}) {
	  $verbose=0;
	} elsif (s{^-n}{-}) {
	  $noact++;
	} elsif (s{^-f}{-}) {
	  $force++;
	} elsif (s{^-s(.+)}{-}s) {
	  $cargo_subcmd = $1;
	} elsif (s{^-([uU])}{-}) {
	  $cargo_lock_update = $1=~m/[a-z]/;
	} elsif (s{^-([cC])}{-}) {
	  $pass_options = $1=~m/[a-z]/;
	} elsif (s{^-D}{-}) {
	  $dump++;
	} elsif (s{^-E}{-}) {
	  $edits_sources++;
	} elsif (s{^-T(.+)}{-}s) {
	  $target = $1;
	} elsif (s{^-([oO])}{-}) {
	  $online = $1=~m/[a-z]/;
	} else {
	  die "$self: unknown short option(s) $_\n" unless $_ eq $orgopt;
	  $not_a_nailing_opt->();
	}
      }
    } elsif (s{^--help$}{}) {
      print_usage();
    } elsif (s{^--(?:doc|man|manual)?$}{}) {
      show_manual();
    } elsif (s{^--target=}{}) {
      $target = $_;
    } elsif (m{^--(on|off)line$}) {
      $online = $1 eq 'on';
    } elsif (m{^--(no-)?git$}) {
      $gitxfer = !$1;
    } elsif (m{^--just-git$}) {
      $just_linkfarm = 1;
      $cargo_lock_update= 1; # will set $linkfarm_detph to 1 by default
      $linkfarm_depth = 'git';
      $gitxfer = 1;
    } elsif (m{^--just-linkfarm(?:=(shallow|git|full))?$}) {
      $just_linkfarm = 1;
      $linkfarm_depth = $1 if $1;
      $cargo_lock_update= 1; # will set $linkfarm_detph to 1 by default
    } elsif (m{^--linkfarm(?:=(no|shallow|git|full))?$}) {
      $linkfarm_depth = $1 || 'git';
    } elsif (m{^--edits?-sources?$}) {
      $edits_sources++;
    } elsif (m{^--force$}) {
      $force++;
    } elsif (m{^--just-run$}) {
      $do_nail = $do_cargo_lock = $do_lock = $gitxfer = 0;
    } elsif (m{^--subdir=(.*)$}) {
      $clisubdir = $1;
      die "$self: --subdir value must be relative\n" if $clisubdir =~ m,^/,;
      $clisubdir =~ s,/$,,;
      $clisubdir = $clisubdir.'/';
    } elsif (m{^--chdir=(.*)$}) {
      $chdir = $1;
    } elsif (m{^--(clean|keep)-linkfarm$}) {
      $oot_clean = $1 eq 'clean';
    } elsif (m{^--(no-)?preclean-build$}) {
      $oot_preclean = $1 ? 'no' : 'src';
    } elsif (m{^--preclean(?:-build)?(?:=(no|src|full))?$}) {
      $oot_preclean = $1 // 'src';
    } elsif (m{^--(no-)?nail$}) {
      $do_nail = !$1;
    } elsif (m{^--(no-)?cargo-lock-manip$}) {
      $do_cargo_lock = !$1;
    } elsif (m{^--(no-)?concurrency-lock$}) {
      $do_lock = !$1;
    } elsif (m{^--leave-nailed$}) {
      $leave_nailed = 1;
    } elsif (s{^--nailfile=}{}) {
      $nailfile = $_;
    } elsif (s{^--subcommand-props=}{}) {
      my @props = split /\,/, $_;
      our %subcmd_prop_ok;
      if (!%subcmd_prop_ok) {
	foreach my $v (\@subcmd_xprops, values %subcmd_props) {
	  $subcmd_prop_ok{$_}=1 foreach @$v;
	};
      }
      $subcmd_prop_ok{$_}
	or die "$self: unknown subcommand property \`$_'\n"
	foreach @props;
      $cargo_subcmd = \@props;
    } elsif (m{^--(no-)?cargo-lock-update}) {
      $cargo_lock_update= !!$1;
    } else {
      $not_a_nailing_opt->();
    }
  }

  $is_cargo // die;
  @ARGV || die;

  if (defined $gitxfer) {
  } elsif (stat ".git") {
    $gitxfer = 1;
  } elsif ($! == ENOENT) {
    $gitxfer = 0;
  } else {
    die "$self: checking for .git (for default value of --git): $!\n";
  }

  $src_absdir = getcwd() // die "$self: getcwd failed: $!\n";
  
  if ($gitxfer) {
    $?=0; $!=0;
    my $cdup = `git rev-parse --show-cdup` // die $!;
    $? and die "git rev-parse --show-cdup: $?";
    chomp $cdup;
    if (length $cdup) {
      chdir $cdup // die "cd $cdup (from $subdir) $!";
      my $topdir = getcwd; $topdir // die "getcwd topdir $!";
      my $prefix = "$topdir/";
      print STDERR "nailing-cargo: toplevel is $topdir ($cdup)\n";
      substr($src_absdir, 0, length $prefix) eq $prefix
	or die "dir confusion: $src_absdir doesn't start with $prefix ?";
      $chdir //= substr($src_absdir, length $prefix);
      $src_absdir = $topdir;
    }
  }

  $worksphere = $src_absdir;
  $worksphere =~ s{/([^/]+)$}{}
    or die "$self: cwd \`$worksphere' unsupported!\n";
  $subdir = $1; # leafname

  $chdir //= '';

  if ($is_cargo) {
    @args_preface = shift @ARGV;
    while (defined($_ = shift @ARGV)) {
      if (!m{^-|^\0?\+}) { unshift @ARGV, $_; last; }
      if ($_ eq '--') { last; }
      push @args_preface, $_;
    }
    @ARGV || die "$self: need cargo subcommand\n";
    $cargo_subcmd //= $ARGV[0];
    $pass_options //= 1;
  } else {
    $cargo_subcmd //= '';
    $pass_options //= 0;
  }
  push @args_preface, shift @ARGV;

  if (!ref($cargo_subcmd)) {
    print STDERR " cargo_subcmd lookup $cargo_subcmd\n" if $dump;
    $cargo_subcmd = $subcmd_props{$cargo_subcmd} // [ ];
  }

  print STDERR " cargo_subcmd props @$cargo_subcmd\n" if $dump;
  my %cargo_subcmd;
  $cargo_subcmd{$_} = 1 foreach @$cargo_subcmd;
  $cargo_subcmd = \%cargo_subcmd;
}

parse_args();
loadconfigs();
readnail();
takelock();
consider_alt_cargo_lock();
consider_oot();
readorigs();
calculate();
addargs();
consider_directories();
our @display_cmd = @ARGV;
oot_massage_cmdline();
setenvs();

if ($dump) {
  eval '
    use Data::Dumper;
    print STDERR Dumper(\%manifests) if $dump>=2;
    print STDERR Dumper(\%packagemap, \@args_preface, \@ARGV,
                        { src_absdir => $src_absdir,
                          worksphere => $worksphere,
                          subdir => $subdir,
                          oot_dir => $oot_dir,
                          oot_absdir => $oot_absdir,
                          build_absdir => $build_absdir,
                          gitxfer => $gitxfer,
                          linkfarm_depth => $linkfarm_depth,
                          oot_preclean => $oot_preclean,
                          force => $force,,
                          forced => $forced,});
  ' or die $@;
}

exit 0 if $noact;

$want_uninstall = !$leave_nailed;
makebackups();
install();

printf STDERR "$self: nailed (%s manifests, %s packages)%s\n",
  (scalar keys %manifests), (scalar keys %packagemap),
  (defined($alt_cargo_lock) and ", using `$alt_cargo_lock'")
  if $verbose && $do_nail;

print STDERR "$self: invoking: @display_cmd\n" if $verbose;
my $estatus = invoke();

files_return_after_update();

uninstall() unless $leave_nailed;
$want_uninstall = 0;

print STDERR "$self: ".(%manifests ? "unnailed" : "finished")
             .".  status $estatus.\n" if $verbose;

exit $estatus;
