1#! @perl@/bin/perl -w
2
3use strict;
4use DBI;
5use DBD::SQLite;
6use String::ShellQuote;
7use Config;
8
9my $program = $ARGV[0];
10
11my $dbPath = "@dbPath@";
12
13my $dbh = DBI->connect("dbi:SQLite:dbname=$dbPath", "", "")
14 or die "cannot open database `$dbPath'";
15$dbh->{RaiseError} = 0;
16$dbh->{PrintError} = 0;
17
18my $system = $ENV{"NIX_SYSTEM"} // $Config{myarchname};
19
20my $res = $dbh->selectall_arrayref(
21 "select package from Programs where system = ? and name = ?",
22 { Slice => {} }, $system, $program);
23
24my $len = !defined $res ? 0 : scalar @$res;
25
26if ($len == 0) {
27 print STDERR "$program: command not found\n";
28} elsif ($len == 1) {
29 my $package = @$res[0]->{package};
30 if ($ENV{"NIX_AUTO_RUN"} // "") {
31 if ($ENV{"NIX_AUTO_RUN_INTERACTIVE"} // "") {
32 while (1) {
33 print STDERR "'$program' from package '$package' will be run, confirm? [yn]: ";
34 chomp(my $comfirm = <STDIN>);
35 if (lc $comfirm eq "n") {
36 exit 0;
37 } elsif (lc $comfirm eq "y") {
38 last;
39 }
40 }
41 }
42 exec("nix-shell", "-p", $package, "--run", shell_quote("exec", @ARGV));
43 } else {
44 print STDERR <<EOF;
45The program '$program' is not in your PATH. You can make it available in an
46ephemeral shell by typing:
47 nix-shell -p $package
48EOF
49 }
50} else {
51 if ($ENV{"NIX_AUTO_RUN"} // "") {
52 print STDERR "Select a package that provides '$program':\n";
53 for my $i (0 .. $len - 1) {
54 print STDERR " [", $i + 1, "]: @$res[$i]->{package}\n";
55 }
56 my $choice = 0;
57 while (1) { # exec will break this loop
58 no warnings "numeric";
59 print STDERR "Your choice [1-${len}]: ";
60 # 0 can be invalid user input like non-number string
61 # so we start from 1
62 $choice = <STDIN> + 0;
63 if (1 <= $choice && $choice <= $len) {
64 exec("nix-shell", "-p", @$res[$choice - 1]->{package},
65 "--run", shell_quote("exec", @ARGV));
66 }
67 }
68 } else {
69 print STDERR <<EOF;
70The program '$program' is not in your PATH. It is provided by several packages.
71You can make it available in an ephemeral shell by typing one of the following:
72EOF
73 print STDERR " nix-shell -p $_->{package}\n" foreach @$res;
74 }
75}
76
77exit 127;