#! /usr/bin/perl
# $Id: transfugdrake 225160 2007-07-31 14:15:56Z blino $

#
# Yves Duret (yduret at mandrakesoft.com)
# Christian Belisle (cbelisle at mandrakesoft.com)
#
# Copyright 2001 MandrakeSoft
#
# This software may be freely redistributed under the terms of the GNU
# public license.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
use lib q(/usr/lib/libDrakX);

## Includes
use common;
use interactive;
use standalone;
use fsedit qw(:read_partitions);
use detect_devices;
use transfugdrake;

# TODO TODO TODO
# Add a variable and a detection for Windows version

## Variables
my $version = 0.3; 		# Version number
my $debug = 1;			# Debug flag
my $windowsxp = 0;              # Flag to know if we have win xp
my $laststep = "";

# Array used to locate the documents.
my @documents_folders =
('My Documents',		# 95,98 - English
 'Documents and Settings');	# XP - French & English

# Ignored users in the document folder (XP)
my @ignored_document_folders =
('LocalService',
 'NetworkService',
 'Owner',
 '.',
 '..');
   
# Address book location
my $address_book_location = "Application Data/Microsoft/Address Book";

# If it's started during install, die.
$::isInstall and die "Not supported during install.\n";

$::isEmbedded = ($::XID, $::CCPID) = "@ARGV" =~ /--embedded (\w+) (\w+)/;

# Application initialization
my $in = interactive::vnew(su);

local $_ = join '', @ARGV;

/-h/ and die "usage: transfug [--version]\n";
/-version/ and die 'transfugdrake '.$version."\n";
$::isEmbedded or $::isWizard = 1;
$::Wizard_pix_up = "wiz_drakgw.png";
$::Wizard_title = N("Transfugdrake");
$::direct = /-direct/;

#- **********************************
#- * 0th step: verify if we are already set up
begin:

$::Wizard_no_previous = 1;

#- **********************************
#- * 0th step: Welcome page
step_0:
if($debug) { print "- Starting Transfugdrake\n"; }

#my %linux_config = transfugdrake::get_linux_config();
 
$::direct or $in->ask_okcancel(N("Transfugdrake"),
N("Welcome to Transfugdrake! I will help you to ease the step windows-linux
by migrating your documents, mails and address books"), 1) or quit_global($in, 0);

#- **********************************
#- * 1st step: Windows configuration
step_1:
if($debug) { print "- Getting Windows Configuration\n"; }
my ($win_partition, $win_fstype, $win_mountpoint) = transfugdrake::get_windows_config($in);
$laststep = "step_1";

#- **********************************
#- * 2nd step: Windows User Chooser
step_2:
my $notvalid = 0;
my $addbook = "";
my $addbook_folder_win95 = "$windows_config->{mountpoint}/WINDOWS/Application Data/Microsoft/Address Book";

if($debug) { print "- Windows User Chooser page\n"; }

if($debug) { print "-- Looking where is the document folder $win_mountpoint\n"; }
my $document_location = get_documents_folder(@documents_folders, $win_mountpoint);

if($document_location eq "") {
    $in->ask_warn(N("Can't find documents folder!"),
                  N("Can't find the folder where the documents are located. Exiting..."));
    quit_global($in, 0);
}

if($debug) { print "-- Looking which Windows version we have\n"; }

# Initialize the users array
@users = ();

if($document_location eq $win_mountpoint.'/'.$documents_folders[0]) { 
    # For 95-98, go see in the address books folder to get the users
    if($debug) { print "--- Windows 95/98 found\n"; }
    opendir YREP, $addbook_folder_win95 or die "unable to open dir: $!\n";
    my @addbook_files = grep /.*dbx$/, readdir YREP;
    closedir YREP;
    foreach my $addbook (@addbook_files) {
        $addbook =~ s/.wab//g;
        foreach my $tmp_ignored (@users) {
            if($addbook eq $tmp_ignored) { $notvalid = 1; }
        }
        if($notvalid != 1) { push(@users, $addbook); }
	$notvalid = 0;
    }
}
elsif($document_location eq $win_mountpoint.'/'.$documents_folders[1]) {
    # For XP, go see in the documents folder to get the directory listing
    if($debug) { print "--- Windows XP found\n"; }
    $in->ask_warn(N("No mail migration available"),
                  N("Warning: Windows XP detected. No mail migration available yet for your Windows version."));
    $windowsxp = 1;
    opendir YREP, $document_location or die "unable to opendir: $!\n";
    my @tmp_user_array = readdir YREP;
    closedir YREP;
    foreach my $tmp_user (@tmp_user_array) {
        foreach my $tmp_ignored (@ignored_document_folders) {
            if ($tmp_user eq $tmp_ignored) { $notvalid = 1; }
        }
        if($notvalid != 1) { push(@users, $tmp_user); }
        $notvalid = 0;
    }
}

if($users[0] eq "") {
    $in->ask_warn(N("No user found!"),
                  N("Can't find any user on your Windows partition. Will copy all documents from Windows"));
}
else {
    $::Wizard_no_previous = 0;
    my $chosen_user = $in->ask_from_list(N("Transfugdrake"),
    N("You have the following users in Windows. Which one do you want to use for migration?"),
    [ @users ], $users[0]) or goto step_0;
}

$laststep = "step_2";
    
#- **********************************
#- * 3rd step: Task Chooser
step_3:
my @tasks = ('Copy files and folders from your Windows partition');

if($debug) { print "- Task Chooser\n"; }

$document_location .= '/'.$chosen_user;
#if(-f $win_mountpoint."/WINDOWS".$address_book_location.$chosen_user.".wab" ||
#   -f $document_location.'/'.$address_book_location.'/'.$chosen_user.".wab") {
	#    push(@tasks, "Migrate address book from Windows (not implemented yet)");
	#}

# This is the Windows XP mailbox checkup. Will be active as soon as transfug_oe support OE 6.
#if(-d $document_location."/Local Settings/Application Data/Identities") {
	#    opendir YREP, $document_location."/Local Settings/Application Data/Identities" or die "unable to opendir: $!\n";
	#    my @identity = readdir YREP;
	#    closedir YREP;
	#    if(-f $document_location."/Local Settings/Application Data/Identities/".$identity[2]."/Microsoft/Outlook Express/Inbox.dbx") {
		#        push(@tasks, "Migrate your mail messages from Windows (Outlook Express 4 & 5 ONLY)");
		#    }
		#}
if(-d $win_mountpoint."/WINDOWS/Application Data/Identities") {
    opendir YREP, $win_mountpoint."/WINDOWS/Application Data/Identities" or die "unable to opendir: $!\n";
    my @identity = readdir YREP;
    closedir YREP;
    if(-f $win_mountpoint."/WINDOWS/Application Data/Identities/".$identity[2]."/Microsoft/Outlook Express/Inbox.dbx") {
        push(@tasks, "Migrate your mail messages from Windows (Outlook Express 4.5 & 5 ONLY)");
    }
}

my $chosen_task = $in->ask_from_list(N("Transfugdrake"),
N("Welcome to TransfugDrake! You are now able to ease\n the step Windows-Linux with many migrations. Please choose what you\n want to do:"), [ @tasks ], $tasks[0]) or quit_global($in, 0);

if($chosen_task eq "Copy files and folders from your Windows partition") { goto step_4; }
#if($chosen_task eq "Migrate address book from Windows (not implemented yet)") { goto step_7; }
if($chosen_task eq "Migrate your mail messages from Windows (Outlook Express 4.5 & 5 ONLY)") { goto step_6; }
$laststep = "step_3";

#- **********************************
#- * 4th step: Copy Windows Files
step_4:
if($debug) { print "- Ready to copy all the documents, waiting for user response\n"; }

copy_documents($document_location, $ENV{HOME});
$laststep = "step_4";

#- ******************************
#- * 5th step: redo if needed
step_5:

if($in->ask_yesorno(N("Transfugdrake"),
N("Do you want to copy other files from another folder?"), 1)) {
    goto step_2;
}
$laststep = "step_5";

#- *******************************
#- * 4th step: mail from windows
step_6:

if ($windowsxp) { goto step_8; }
$::direct or $in->ask_okcancel(N("Transfug"),
N("We will bring back your Outlook Mailboxes to a standard unix mbox\n
NB: This feature works only with Outlook Express 4.5 and 5"), 1) or goto step_7;

mkdir "$ENV{HOME}/Mail" unless (-e "$ENV{HOME}/Mail");

$oe5onwin98="$win/WINDOWS/Application Data/Identities";
opendir YREP, $oe5onwin98;
my @tmp_identitity = readdir YREP;
closedir YREP;
$oe5onwin98 .= '/'.$tmp_identity[2]."/Microsoft/Outlook Express";

if (-e $oe5onwin98) {
    print "OE detected\n";
    opendir YREP, $oe5onwin98 or die "unable to open dir: $!";
    @files = grep /.*dbx$/, readdir YREP;
    closedir YREP;
    foreach $i (@files) {
	`transfug_oe \"$oe5onwin98/$i\" \"$ENV{HOME}/Mail/$i\"`;
    }
}
$laststep = "step_6";

#- *******************************
#- * 6th step: address book from windows
# In XP, address book is located in /Document and Settings/user/Appli Data/Microsoft/Address Book/
#step_7:

#$::direct or $in->ask_okcancel(N("Transfugdrake"),
#N("Here will come the address book migration page."), 1) or quit_global($in, 0);

#- *******************************
#- * 8th step: finish
step_8:
$::Wizard_no_previous = 0;
$::direct or $in->ask_okcancel(N("Transfugdrake"),
N("The migration of all of your Windows data is finished."), 1) or goto $laststep; 

#- *******************************
#-          FUNCTIONS
#- *******************************
sub detect_partition {
    # Return array
    my @win;

    # TODO TODO TODO TODO TODO TODO TODO TODO
    #   - Print partition type beside the partition
    #   - Mount the partition the user want.
    #   - Detect partition as user, and ask root passwd only when needed

    # Get folder listing in /mnt
    my @mnt_dir_folder = split("\n", `ls /mnt/`);

    # Look in the array if we have a windows partition
    my $folders_count = 1;
    while(@mnt_dir_folder[$folders_count] ne "") {
       push(@win,"/mnt/".@mnt_dir_folder[$folders_count]);
       $found = 1;
       if($debug) { print "-- Found windows partition at /mnt/@mnt_dir_folder[$folders_count]\n"; }
       $folders_count++;
    }
    
    # If nothing is found, print an error and exit.
    if(!$found) {
        print "- No windows partitions\n";
        $in->ask_warn(N("Can't find windows!"),
            N("Sorry, I can't find windows. Maybe it's not installed, or your windows partition is not mounted on Mandrake."));
         quit_global($in);
    }
    else {
        return @win;
    }
}

sub get_documents_folder {
    my @doc_folders = @_;
    my $mountpoint = "";

    # Last entry in @doc_folders is moved to $mountpoint.
    $mountpoint = pop(@doc_folders);
    $mountpoint .= '/';

    # Make a whole checkup to see where My Documents is located.
    foreach my $test_doc (@doc_folders) {
       if(-d $mountpoint.$test_doc) {
           if(debug) { print "-- $mountpoint$test_doc found\n"; }
	   if($test_doc eq $doc_folders[2]) { $xp = 1; }
           return $mountpoint.$test_doc;
       }
    }
}

sub copy_documents {
    my $source = $_[0];
    my $dest = $_[1];
 
    mkdir("$dest/win_backup");
    $dest .= "/win_backup";

    $::Wizard_no_previous = 1;
    if(!($in->ask_yesorno(N("Transfugdrake"),
                    N("Do you want to copy all the content of\n \"$source\" to\n \"$dest\"?"), 1))) {
        goto step_5;
    }
    $wait_configuring = $in->wait_message(N("Copying files..."),
     N("Copying all files from $source to $dest. This may take several minutes."));
    
    $source =~ s/\ /\\ /g;
    system("cp -R $source $dest");
    undef $wait_configuring;
}

1;
