#!/usr/bin/perl -w
# (c) Copyright 2001-2008. CodeWeavers, Inc.
use strict;


# Portable which(1) implementation
sub cxwhich($$;$)
{
    my ($dirs, $app, $noexec)=@_;
    if ($app =~ /^\//)
    {
        return $app if ((-x $app or $noexec) and -f $app);
    }
    elsif ($app =~ /\//)
    {
        require Cwd;
        my $path=Cwd::cwd() . "/$app";
        return $path if ((-x $path or $noexec) and -f $path);
    }
    else
    {
        foreach my $dir (split /:/, $dirs)
        {
            return "$dir/$app" if ($dir ne "" and (-x "$dir/$app" or $noexec) and -f "$dir/$app");
        }
    }
    return undef;
}

# Fast dirname() implementation
sub _cxdirname($)
{
    my ($path)=@_;
    return undef if (!defined $path);
    return "." if ($path !~ s!/+[^/]+/*$!!s);
    return "/" if ($path eq "");
    return $path;
}

# Locate where CrossOver is installed by looking for the directory
# where this this script is located, unwinding symlinks on the way
sub locate_cx_root()
{
    if (!defined $ENV{CX_ROOT})
    {
        my $argv0=cxwhich($ENV{PATH},$0);
        $argv0=$0 if (!defined $argv0);
        if ($argv0 !~ m+^/+)
        {
            require Cwd;
            $argv0=Cwd::cwd() . "/$argv0";
        }
        my $dir=_cxdirname($argv0);
        while (!-x "$dir/cxmenu" or !-f "$dir/cxmenu")
        {
            last if (!-l $argv0);
            $argv0=readlink($argv0);
            $argv0="$dir/$argv0" if ($argv0 !~ m+^/+);
            $dir=_cxdirname($argv0);
        }
        $dir =~ s%(/\.)*$%%;
        $dir =~ s%(/\./(\./)*)%/%;
        $ENV{CX_ROOT}=_cxdirname($dir);
    }
    if (!-x "$ENV{CX_ROOT}/bin/cxmenu" or !-f "$ENV{CX_ROOT}/bin/cxmenu")
    {
        my $name0=$0;
        $name0 =~ s+^.*/++;
        print STDERR "$name0:error: could not find CrossOver in '$ENV{CX_ROOT}'\n";
        exit 1;
    }
    return $ENV{CX_ROOT};
}

BEGIN {
    unshift @INC, locate_cx_root() . "/lib/perl";
}
use CXLog;
use CXUtils;


# Process command-line options
my $opt_command;
my $opt_verbose;
my $opt_help;
my $opt_inline;
require CXOpts;
my $cxopts=CXOpts->new(["stop_on_non_option"]);
$cxopts->add_options(["inline"     => \$opt_inline,
                      "verbose!"   => \$opt_verbose,
                      "?|h|help"   => \$opt_help
                     ]);
my $err=$cxopts->parse();
CXLog::fdopen(2) if ($opt_verbose);
$opt_command=join(' ',@ARGV);

# Validate the command line options
my $usage;
if ($err)
{
    cxerr("$err\n");
    $usage=2;
}
elsif ($opt_help)
{
    $usage=0;
}
elsif (!defined $opt_command or $opt_command eq "")
{
    cxerr("no command specified\n");
    $usage=2;
}

# Print usage
if (defined $usage)
{
    my $name0=cxname0();
    if ($usage)
    {
        cxerr("try '$name0 --help' for more information\n");
        exit $usage;
    }
    print "Usage: $name0 [--inline] [--verbose] COMMAND\n";

    print "\n";
    print "Starts a graphical interface to perform an su and run the specified\n";
    print "application as root.\n";

    print "\n";
    print "Options:\n";
    print "  COMMAND     The command to run as root\n";
    print "  --inline    Use the current stdin and stdout for the password prompt\n";
    print "              and command rather than launching a GUI prompt\n";
    print "  --verbose   Output more information about what is going on\n";
    print "  --help, -h  Shows this help message\n";
    exit 0;
}

if ($> == 0)
{
    # We are already root, so just run the command
    cxexec($opt_command);
    cxerr("unable to run '$opt_command': $!\n");
    exit 1;
}

my @args;
if (!$opt_inline)
{
    my @su_list=("xdg-su -c");
    # Try to pick the appropriate default for the current desktop environment
    push @su_list, "gksu" if ($ENV{GNOME_DESKTOP_SESSION_ID});
    push @su_list, "kdesu -c" if ($ENV{KDE_FULL_SESSION});
    # And push all known tools as fallbacks
    push @su_list, "gksu", "kdesu -c";

    foreach my $sutool_cmd (@su_list)
    {
        my @sutool=CXUtils::cmdline2argv($sutool_cmd);
        cxlog("trying '$sutool[0]'\n");
        my $path=cxwhich($ENV{PATH}, $sutool[0]);
        if (defined $path)
        {
            @args=(@sutool, $opt_command);
            last;
        }
    }
    if (!@args)
    {
        @args=CXUtils::get_terminal_emulator(cxgettext("Enter the root password"));
        if (!@args)
        {
            cxerr("unable to find a suitable terminal emulator\n");
            exit 1;
        }
        push @args,"-e","$0";
        push @args,"--inline";
        push @args,$opt_command;
        cxexec(@args);
        cxerr("unable to run '@args': $!\n");
        exit 1;
    }
}

if (!@args)
{
    $opt_inline=1;
    print cxgettext("This operation must be run as root:\n");
    # Use sudo if available and allowed
    my $sudo_path=cxwhich("$ENV{PATH}","sudo");
    if (defined $sudo_path)
    {
        my $cmd=shquote_string($sudo_path) . " -l 2>/dev/null |";
        if (open(my $fh, $cmd))
        {
            if (grep /^\s*\((?:root|ALL)\)\s+(?:NOPASSWD:\s+)?ALL\s*$/, <$fh>)
            {
                @args=($sudo_path,"-H","/bin/sh","-c",$opt_command);
            }
            close($fh);
        }
    }
    if (!@args)
    {
        # Try sux first as it will preserve access to X
        my $sux_path=cxwhich("$ENV{PATH}","sux");
        if (defined $sux_path)
        {
            @args=("sux","-","root",$opt_command);
        }
    }
    if (!@args)
    {
        # Otherwise, use the regular su
        @args=("su","-","root","-c",$opt_command);
    }
    print join(" ", map { /[ "\$]/ ? shquote_string($_) : $_ } @args), "\n";
}

my $rc = cxsystem(@args);
if ($opt_inline)
{
    print cxgettext("Finished. Press Return to continue.");
    <STDIN>;
}

# Sanitize $rc so it is suitable for exit
exit($rc >> 8) if ($rc >> 8);
exit($rc);
