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

my $name0=$0;
$name0=~ s+^.*/++;


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

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

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


# Process command-line options
use CXOpts;
my $opt_device;
my $opt_xterm;
my $opt_verbose;
my $opt_help;
my $cxopts=CXOpts->new();
$cxopts->add_options(["d|device=s" => \$opt_device,
                      "xterm"      => \$opt_xterm,
                      "verbose!"   => \$opt_verbose,
                      "?|h|help"   => \$opt_help
                     ]);
my $err=$cxopts->parse();
CXLog::fdopen(2) if ($opt_verbose);


# Validate the command line options
my $usage;
if ($err)
{
    print STDERR "$name0:error: $err\n";
    $usage=2;
}
elsif ($opt_help)
{
    $usage=2;
}
elsif (defined $opt_device and !-e $opt_device)
{
    print STDERR "$name0:error: '$opt_device' does not exist\n";
    $usage=2;
}

# Print usage
if ($usage)
{
    print STDERR "Usage: $name0 [--xterm] [--device device] [--verbose]\n";
    exit 2;
}

# Recurse inside an xterm
if ($opt_xterm)
{
    my @args=CXUtils::get_terminal_emulator("CrossOver - Fixing /etc/fstab");
    if (!@args)
    {
        print STDERR "$name0:error: unable to find a suitable terminal emulator\n";
        exit 1;
    }
    push @args,"-e","$0";
    push @args,"--device",$opt_device if ($opt_device);
    exec @args
    or print STDERR "$name0:error: unable to run '@args': $!\n";
}


# Parse /etc/fstab and modify it
if (!open FILE, "/etc/fstab")
{
    print STDERR "$name0:error: unable to open /etc/fstab: $!\n";
    exit 1;
}

my %chmods;
my @lines;
my $modified;
my $modified_supermount;
foreach my $line (<FILE>)
{
    push @lines, $line;
    next if ($line =~ /^\s*\#/);

    my $entry = $line;
    $entry =~ s/(\#.*)$//;
    my @fields = split /\s+/, $entry;

    # Check whether this
    if ((@fields < 4) ||
        ($fields[2] !~ /\biso9660\b/ and
         $fields[2] ne "auto" and
         $fields[2] ne "supermount")
       )
    {
        next;
    }

    # Parse the options to get the device
    my @options=split /,/, $fields[3];
    my $device=$fields[0];
    if ($fields[2] eq "supermount")
    {
        my $opt=(grep /^dev=/,@options)[0];
        if (defined $opt)
        {
            $device=$opt;
            $device =~ s/^dev=//;
        }
    }

    # Skip non-cd lines
    if ($fields[2] eq "auto" or $fields[2] eq "supermount")
    {
        if ($device !~ /cdr/ and $fields[1] !~ /cdr/ and
            $device !~ /dvd/ and $fields[1] !~ /dvd/)
        {
            next;
        }
    }
    if (defined $opt_device and $device ne $opt_device and
        $fields[2] eq "supermount")
    {
        next;
    }

    # Add the device for permission fixing
    $chmods{$device}=1 if (!-r $device );

    # Try to determine where to insert the new options
    my $index=0;
    for (my $i=0;$i<@options;$i++)
    {
        if ($options[$i] eq "--")
        {
            $index=$i+1;
            last;
        }
    }

    # Insert unhide and user if needed
    if (!grep /^unhide$/, @options)
    {
        splice @options, $index, 0, "unhide";
        $modified_supermount=1 if ($fields[2] eq "supermount");
    }
    if ($fields[2] ne "supermount")
    {
        splice @options, $index, 0, "user"   if (!grep /^(no)?user$/, @options);
    }
    my $opts=join(",",@options);
    next if ($fields[3] eq $opts);

    # Modify the line in-place so that we don't loose any of the formatting
    $lines[-1] =~ s/(\s+)\Q$fields[3]\E(\s*)/$1$opts$2/;
    $modified = 1;
}
close FILE;
$chmods{$opt_device}=1 if (defined $opt_device and (!-r $opt_device or !-w $opt_device));

if (!$modified and !%chmods)
{
    print "No modification is necessary.\n";
    print "Type Enter to continue\n";
    my $wait=<>;
    exit 0;
}

my $cmd="";
my $tmpfile;
if ($modified)
{
    print "Generating new fstab file containing the unhide and user options:\n";
    umask(umask() | 0022);
    $tmpfile = "/tmp/fstab.$$";
    if (!open OUT,">$tmpfile")
    {
        print STDERR "$name0:error: unable to create temporary file: $!\n";
        exit 1;
    }
    foreach my $line (@lines)
    {
        print OUT $line;
    }
    close OUT;
    if ($modified_supermount)
    {
        print "\nNote that, because one of the modified entries is a supermount\n";
        print "entry, you may need to reboot for the changes to take effect.\n";
    }
    $cmd =  "mv /etc/fstab /etc/fstab.$$ && cat \"$tmpfile\" > /etc/fstab";

    ## really print the file out from the place it was written
    print "-----------------------------------------------------------------\n";
    if (!open IN,"<$tmpfile")
    {
        print STDERR "$name0:error: unable to read temporary file: $!\n";
        exit 1;
    }
    while( <IN> )
    {
        print;
    }
    close IN;
    print "-----------------------------------------------------------------\n";
    print "Your old fstab will be backed up to /etc/fstab.$$\n";
}

if (%chmods)
{
    my $devices=join(" ",sort keys %chmods);
    print "We need to make the following devices world readable:\n";
    print "$devices\n";
    $cmd .= "; " if ($cmd);
    $cmd .= "chmod ugo+r $devices";
}

print "\nDo you want to make the above modifications [y/N]?\n";
my $answer=<>;
if ($answer =~ /^y(es)?$/i)
{
    # check if we are root or not
    if ($> == 0)
    {
        CXUtils::cxsystem($cmd);
    }
    else
    {
        print "\nEnter the root password to ";
        if ($modified)
        {
            print "write the above to /etc/fstab\n";
            if(%chmods)
            {
                print " and ";
            }
        }
        if (%chmods)
        {
            print "change your cdrom device permissions.\n";
        }
        print "su -c \"$cmd\"\n\n";
        CXUtils::cxsystem("su -c \"$cmd\"");
    }
}

unlink $tmpfile if (defined $tmpfile);
