#!/usr/bin/perl -w
use Getopt::Long;$Getopt::Long::debug=0;

$etcwineconf = '/etc/wine.d//wine.conf';

$dirperms = 0755;

sub usage {
	print <<EoU;
Usage: $0 [--help] [--force] [directory of an existing windows installation]

This script sets up your personal windows directory structure (including
shell folder directories), creates your personal ~/.winerc and, if present,
symlinks files from an existing windows installation to your windows directory
structure.

When run on an previous installation it tries to replace real present files
with symbolic links to the installation if the files are the same to save
diskspace.

This script does some sanity checks which can be overridden by --force.
EoU
	exit;
}

##############################################################################
# (possibly copy) and fix up .winerc
# 

sub fixup_winerc {
	local($domodify) = @_;
	chdir;
	if (! -e '.winerc') {
		system('cp',$etcwineconf,'.winerc');
		print "Copied $etcwineconf to ~/.winerc.\nPlease adapt ~/.winerc to your personal needs.\n";
	}
	return if (!$domodify);

	if (open(WINERC,".winerc") && open(WINERCNEW,">.winerc.new")) {
		$foundW = 0;
		$modified = 0;
		while (<WINERC>) {
			chomp;
			$foundW = 0 if (/^\[/);
			$foundW = 1 if (/^\[Drive W]/);
			if ($foundW && /^Path=(.*)/ && ($1 ne $windowsdir)) {
				print WINERCNEW ";$_\n";
				print WINERCNEW "Path=$windowsdir\n";
				$modified = 1;
				next;
			}
			print WINERCNEW "$_\n";
		}
		close(WINERCNEW);
		close(WINERC);
		if ($modified) {
			rename('.winerc','.winerc.old')||die "rename .winerc .winerc.old:$!\n";
			rename('.winerc.new','.winerc')||die "rename .winerc.new .winerc:$!\n";
			print "Modified entry for [Drive W] (existing windows installation) in your ~/.winerc.\n";
		} else {
			# not needed
			unlink('.winerc.new');
		}
	}
}

##############################################################################
# Create the Windows directory structure
# 
sub create_windows_dirs {
	local($xdir,@dirs);

	# folders needed, also for shell folders.
	@dirs = (
		'',
		'system',
		'Favorites',
		'Start Menu',
		'Start Menu/Programs',
		'Start Menu/Programs/Startup',
		'Desktop',
		'Fonts',
		'SendTo',
		'ShellNew',
		'Recent',
		'NetHood',
		'../My Documents',
	);
	chdir;
	foreach $xdir (@dirs) {
		$xdir="windows/$xdir";
		if (! -d $xdir) {
			if (mkdir($xdir,$dirperms)) {
				print "created directory ~/$xdir\n";
			} else {
				warn "could not create $xdir subdirectory:$!\n";
			}
		}
	}
}
#############################################################################
# link in windows installation
# 

# mkdir calls may fail due to existing directory, ignore that.
# FIXME: copy/link more directories?

sub link_windows_install {
	@xdirs=('','system','system32');
	foreach $xdir (@xdirs) {
		$srcdir = "$windowsdir/$xdir";
		$dstdir = "windows/$xdir";

		if (!chdir($srcdir)) {
			if ($dstdir ne 'windows/system32') {
				warn "could not change directory to $srcdir:$!\n";
			}
			next;
		}
		@files = <*>;
		chdir;
		if (!chdir($dstdir)) {
			warn "could not change directory to ~/$dstdir:$!\n";
			next;
		}
		print "symlinking all files in $srcdir to ~/$dstdir\n";
		foreach $file (@files) {
			next if ($file =~ /tmp$/i);
			if (-d "$srcdir/$file") {
				if (! -d $file) {
					mkdir($file,$dirperms);
					if (-d $file) {
						print "created subdirectory ~/$dstdir/$file\n";
					} else {
						mkdir($file,$dirperms) || warn "mkdir ~/$dstdir/$file failed:$!\n";
					}
				}
				next;
			}
			next if (-l $file); # already symlink? fine ...
			if (! -e $file) {
				if (-f "$srcdir/$file") {
					if (!symlink("$srcdir/$file",$file)) {
						warn "symlink($srcdir/$file <- $file) failed:$!\n";
					}
				}
			} else {
				($dev,$ino,$mode,$nlink,$uid,$gid,$rdev) = stat("$srcdir/$file");	
				($xdev,$xino,$mode,$nlink,$uid,$gid,$xrdev) = stat("$file");	
				next if (($dev==$xdev)&&($ino==$xino)&&($xrdev==$rdev));
				if (!system("cmp $srcdir/$file $file >/dev/null 2>&1")) {
					# not different?
					print "replacing $file by symlink to $srcdir/$file\n";
					unlink($file)||warn "could not unlink $file:$!\n";
					if (!symlink("$srcdir/$file",$file)) {
						warn "symlink($srcdir/$file <- $file) failed:$!\n";
					}
				}
			}
		}
	}
	print "directory contents linked.\n";
}

##############################################################################
#                             Main

Getopt::Long::GetOptions("help"=>\$help,"force"=>\$force);

if ($help) { &usage;exit; }

&create_windows_dirs();

if (defined($ARGV[$[])) {
	$windowsdir = $ARGV[$[];

# Did the user probably specify the root of the drive instead of the windows
# directory? Well, no problem.

	if ( -d "$windowsdir/windows" ) {
		$windowsdir = "$windowsdir/windows";
	}

} else {
	if (open(MOUNTS,"/proc/mounts")) {
		$windowsdir=0;

		while (<MOUNTS>) {
			chomp;
			next if (/^\S*:\S*/); # skip nfs or automounts.
			
			next unless (/^(\S*)\s*(\S*)\s*(\S*)\s*(\S*)/);
			$device		= $1;
			$mountpoint	= $2;
			# $fstype		= $3;
			# $fsoptions	= $4;

			if (	(-d "$mountpoint/windows/") &&
				(-f "$mountpoint/windows/win.ini")
			) {
				$windowsdir = "$mountpoint/windows";
				last;
			}
			if (open(AUTOEXEC,"$mountpoint/autoexec.bat")) {
				while (<AUTOEXEC>) {
					chomp;
					next unless (/C:\\([^\\]*)\\COMMAND/i);
					$xdir="\L$1";
					if (	(-d "$mountpoint/$xdir")&&
						(-f "$mountpoint/$xdir/win.ini")
					) {
						$windowsdir = "$mountpoint/$xdir";
						last;
					}
				}
				close(AUTOEXEC);
				last if ($windowsdir);
			}
			if (open(CONFIGSYS,"$mountpoint/config.sys")) {
				while (<CONFIGSYS>) {
					chomp;
					next unless (/C:\\([^\\]*)\\COMMAND/i);
					$xdir="\L$1";
					if (	(-d "$mountpoint/$xdir")&&
						(-f "$mountpoint/$xdir/win.ini")
					) {
						$windowsdir = "$mountpoint/$xdir";
						last;
					}
				}
				close(CONFIGSYS);
				last if ($windowsdir);
			}
			if (open(MSDOSSYS,"$mountpoint/msdos.sys")) {
				while (<MSDOSSYS>) {
					chomp;
					next unless (/^windir=c:\\(.*)/i);
					$xdir="\L$1";
					if (	(-d "$mountpoint/$xdir")&&
						(-f "$mountpoint/$xdir/win.ini")
					) {
						$windowsdir = "$mountpoint/$xdir";
						last;
					}
				}
				close(MSDOSSYS);
				last if ($windowsdir);
			}
		}
		close(MOUNTS);
	}
	if ($windowsdir) {
		print "detected windows installation on $device ($windowsdir)\n";
	} else {
		&fixup_winerc(0);
		exit;
	}
}

if ( ! -d $windowsdir ) {
	print "You need to specify an absolute directory as argument.\n";
	exit;
}

if ( !$force && (! -e "$windowsdir/win.ini" )) {
	print <<EoX;
$windowsdir does not contain a 'win.ini' file.
If you want to use it as windows base directory anyway, rerun winesetup
with --force.
EoX
	exit;
}
&link_windows_install();
&fixup_winerc(1);
