#!/usr/bin/ruby
# encoding: utf-8

class RescueScreen	
	def initialize(extlayers, button, nwscreen)
		lang = ENV['LANGUAGE'][0..1]
		lang = ENV['LANG'][0..1] if lang.nil?
		lang = "en" if lang.nil?
		@tl = MfsTranslator.new(lang, "RescueScreen.xml")
		### Combo for writeable drives when file managers are selected
		@writeablecombo = nil
		@writeablelist = Array.new
		@writeableparts = Array.new
		# Try to omit opening of firefox when the cloud layer is shown the first time
		@cloudshowcount = 0
		### First panel, selection of tasks
		# First tile, rescue on file system level
		button1 = Gtk::EventBox.new.add Gtk::Image.new("rescuewine.png")
		text1 = Gtk::Label.new
		text1.width_request = 320
		text1.wrap = true
		text1.set_markup("<span foreground='white'><b>" + @tl.get_translation("localhead") + "</b>\n\n" + @tl.get_translation("localbody") + "</span>")
	
		# Second tile, rescue to cloud
		button2 = Gtk::EventBox.new.add Gtk::Image.new("rescueturq.png")
		text2 = Gtk::Label.new
		text2.width_request = 320
		text2.wrap = true
		text2.set_markup("<span foreground='white'><b>" + @tl.get_translation("cloudhead1") + "</b>\n\n"+ @tl.get_translation("cloudbody1") + "</span>")
		
		# Third tile, image 1:1
		button3 = Gtk::EventBox.new.add Gtk::Image.new("rescueorange.png")
		text3 = Gtk::Label.new
		text3.width_request = 320
		text3.wrap = true
		# text3.set_markup("<span foreground='white'><b>Klon Ihrer Festplatte</b>\n\nWählen Sie diese Option bei drohenden Festplattendefekten. Sämtliche Partitionen, Dateien und Programme auf dem Laufwerk werden eins zu eins auf eine externe Festplatte überspielt. Achtung: Alle auf dem Ziel-Laufwerk gespeicherte Daten gehen dadurch verloren!</span>.")
		text3.set_markup("<span foreground='white'><b>" + @tl.get_translation("imagehead") + "</b>\n\n" + @tl.get_translation("imagebody")  + "</span>")
		
		# Fourth tile, clone 1:1
		button4 = Gtk::EventBox.new.add Gtk::Image.new("rescuelight.png")
		text4 = Gtk::Label.new
		text4.width_request = 320
		text4.wrap = true
		# text3.set_markup("<span foreground='white'><b>Klon Ihrer Festplatte</b>\n\nWählen Sie diese Option bei drohenden Festplattendefekten. Sämtliche Partitionen, Dateien und Programme auf dem Laufwerk werden eins zu eins auf eine externe Festplatte überspielt. Achtung: Alle auf dem Ziel-Laufwerk gespeicherte Daten gehen dadurch verloren!</span>.")
		text4.set_markup("<span foreground='white'><b>" + @tl.get_translation("clonehead") + "</b>\n\n" + @tl.get_translation("clonebody")  + "</span>")
		
		@layers = Array.new
		fixed = Gtk::Fixed.new
		fixed.put(button1, 0, 0)
		fixed.put(button2, 0, 130)
		fixed.put(button3, 460, 0)
		fixed.put(button4, 460, 130)
		fixed.put(text1, 130, 0)
		fixed.put(text2, 130, 130)
		fixed.put(text3, 590, 0)
		fixed.put(text4, 590, 130)
		
		TileHelpers.place_back(fixed, extlayers)
		extlayers["rescuestart"] = fixed
		@layers[0] = fixed
		
		button.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				extlayers["rescuestart"].show_all
			end
		}
		button1.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				TileHelpers.umount_all 
				@writeablelist, @writeableparts = reread_targetlist(@writeablecombo)
				extlayers["rescuelocal"].show_all
			end
		}
		button2.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				if nwscreen.test_connection == false
					nwscreen.nextscreen = "rescuecloud"
					nwscreen.fill_wlan_combo 
					# Check for networks first...
					extlayers["networks"].show_all
				else
					extlayers["rescuecloud"].show_all
				end
				
			end
		}
		button3.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				# extlayers["clonesource"].show_all
				extlayers["imagechoice"].show_all
			end
		}
		button4.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				# extlayers["clonesource"].show_all
				extlayers["clonesource"].show_all
			end
		}
		
		#### Screen for filetypes
		locallayers = get_local_layer(extlayers)
		extlayers["rescuelocal"] = locallayers
		@layers[1]  = locallayers

		#### Screen for file manager
		fmlayers = get_fm_layer(extlayers)
		extlayers["rescuefilemanager"] = fmlayers
		@layers[2]  = fmlayers
		
		#### Screen for cloud
		cloudlayer = get_cloud_layer(extlayers)
		extlayers["rescuecloud"] = cloudlayer
		@layers[3] = cloudlayer

	end
	attr_reader :layers
	
	def get_local_layer(extlayers)
		fixed = Gtk::Fixed.new
		TileHelpers.place_back(fixed, extlayers)
		deltext = TileHelpers.create_label("<b>" + @tl.get_translation("targethead") + "</b>\n\n" +@tl.get_translation("targetbody") , 510)
		@writeablecombo = Gtk::ComboBox.new
		@writeablecombo.height_request = 32
		@writeablecombo.width_request = 380
		reread = Gtk::Button.new(@tl.get_translation("reread"))
		reread.width_request = 120
		reread.height_request = 32
		reread.signal_connect('clicked') {
			TileHelpers.umount_all 
			@writeablelist, @writeableparts = reread_targetlist(@writeablecombo)
		}
		text5 = Gtk::Label.new
		text5.width_request = 250
		text5.wrap = true
		text5.set_markup("<span color='white'>" + @tl.get_translation("gotofilemanager") + "</span>")
		forw  = Gtk::EventBox.new.add Gtk::Image.new("forward.png")
		button1 = Gtk::Image.new("rescuegreen.png")
		forw.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				if @writeableparts.size < 1
					TileHelpers.error_dialog(@tl.get_translation("nosuitabledrives"), @tl.get_translation("nosuitablehead"))
				else
					extlayers.each { |k,v|v.hide_all }
					mount_all( @writeableparts[@writeablecombo.active] )
					extlayers["rescuefilemanager"].show_all
					system("su surfer -c 'Thunar /cobi/" + @tl.get_translation("backupdir") + "' &") 
					system("su surfer -c 'Thunar /media/disk' &") 
				end
			end
		}
		fixed.put(button1, 0, 0)
		fixed.put(deltext, 130, 0)
		fixed.put(reread, 520, 118)
		fixed.put(@writeablecombo, 130, 118)
		fixed.put(forw, 853, 282)
		fixed.put(text5, 605, 288)
		return fixed
	end

	# Layer for filemanager
	def get_fm_layer(extlayers)
		fixed = Gtk::Fixed.new
		backbutton = TileHelpers.place_back(fixed, extlayers, false)
		button1 = Gtk::Image.new("rescuegreen.png")
		deltext = TileHelpers.create_label("<b>" + @tl.get_translation("copyhead") + "</b>\n\n" + @tl.get_translation("copybody") , 510)
		thbutton = Gtk::Button.new(@tl.get_translation("openfilemanager"))
		thbutton.width_request = 150
		thbutton.height_request = 32
		thbutton.signal_connect('clicked') {
			system("su surfer -c 'Thunar /media' &") 
		}
		backbutton.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				system("killall Thunar")
				system("killall -9 Thunar")
				TileHelpers.umount_all
				extlayers["start"].show_all
			end
		}
		fixed.put(button1, 0, 0)
		fixed.put(deltext, 130, 0)
		fixed.put(thbutton, 490, 128)
		return fixed
	end

	def get_cloud_layer(extlayers)
		fixed = Gtk::Fixed.new
		backbutton = TileHelpers.place_back(fixed, extlayers, false)
		button1 = Gtk::Image.new("rescuegreen.png")
		deltext = TileHelpers.create_label("<b>" + @tl.get_translation("cloudhead") + "</b>\n\n" + @tl.get_translation("cloudbody"), 510)
		ffbutton =Gtk::Button.new(@tl.get_translation("openfilemanager"))
		ffbutton.width_request = 150
		ffbutton.height_request = 32
		# Dropdown for preconfigured cloud services
		clouddrop = Gtk::ComboBox.new
		clouddrop.width_request = 425
		droplabel = TileHelpers.create_label(@tl.get_translation("cloudservice"), 80)
		# Add default texts
		cloudservices = [ "Google Drive", # FUSE
			"Microsoft OneDrive", # FUSE
			"T-Online Mediacenter", # DAV
			"GMX Mediacenter",  # DAV
			"1&1 SmartDrive",  # DAV
			"Strato HiDrive", # DAV
			"WEB.de", # DAV
			"DropBox", # Website
			"F-Secure Younited", # Webseite
			"Apple iCloud", # Webseite 
			"Amazon cloud drive", # Webseite 
			@tl.get_translation("other_website"),  
			@tl.get_translation("other_webdav")
		]
		davurls = [ 
			"https://drive.google.com/", 
			"https://onedrive.live.com/", 
			"https://webdav.mediencenter.t-online.de/", 
			"https://webdav.mc.gmx.net/", 
			"https://webdav.office.1und1.de/", 
			"https://webdav.hidrive.strato.com/", 
			"https://webdav.smartdrive.web.de/",
			"https://www.dropbox.com/de",
			"https://www.younited.com/de/fur-sie",
			"https://www.icloud.com/",
			"https://www.amazon.de/clouddrive/home/",
			nil, 
			nil 
		] 
		cloudservices.each { |s| clouddrop.append_text(s) }
		
		# Servername (optional)
		cloudserver = Gtk::Entry.new
		cloudserver.width_request = 425
		cloudserver.text = "https://my.owncloud.abc/"
		serverlabel = TileHelpers.create_label(@tl.get_translation("cloudserver"), 80)
		# Auth token (optional)
		cloudtoken = Gtk::Entry.new
		cloudtoken.width_request = 340
		tokenlabel = TileHelpers.create_label(@tl.get_translation("cloudtoken"), 80)
		tokenbutton = Gtk::Button.new(@tl.get_translation("createtoken"))
		tokenbutton.width_request = 80
		# Username
		clouduser = Gtk::Entry.new
		clouduser.width_request = 425
		userlabel = TileHelpers.create_label(@tl.get_translation("clouduser"), 80)
		# Password
		cloudpass = Gtk::Entry.new 
		cloudpass.width_request = 425
		cloudpass.visibility = false 
		passlabel = TileHelpers.create_label(@tl.get_translation("cloudpass"), 80)
		clouddrop.active = 0 
		cloudserver.visible = false
		serverlabel.visible = false
		cloudserver.sensitive = false
		clouddrop.signal_connect('changed') { 
			ffbutton.label = @tl.get_translation("openfilemanager")
			if clouddrop.active == cloudservices.size - 1
				cloudserver.sensitive = true
				cloudserver.visible = true
				serverlabel.visible = true
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = true }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			elsif clouddrop.active == cloudservices.size - 2
				ffbutton.label = @tl.get_translation("openfirefox")
				cloudserver.sensitive = false
				cloudserver.visible = false
				serverlabel.visible = false
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = false }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			#elsif clouddrop.active == 0
			#	cloudserver.sensitive = false
			#	cloudserver.visible = false
			#	serverlabel.visible = false
			#	[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = false }
			#	[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = true }
			elsif clouddrop.active > 6 || clouddrop.active == 0 || clouddrop.active == 1
				ffbutton.label = @tl.get_translation("openfirefox")
				cloudserver.sensitive = false
				cloudserver.visible = false
				serverlabel.visible = false
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = false }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }	
			else
				cloudserver.sensitive = false
				cloudserver.visible = false
				serverlabel.visible = false
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = true }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			end
		}
		tokenbutton.signal_connect('clicked') {
			url = nil
			IO.popen("gdfstool auth -u") { |l|
				while l.gets
					url = $_.strip if $_ =~ /^https/ 
				end
			}
			if url.nil?
				TileHelpers.error_dialog(@tl.get_translation("gdfs_auth_failed"))
			else
				system("su surfer -c \"firefox '#{url}' &\"")
			end
		}
		ffbutton.signal_connect('clicked') {
			if clouddrop.active == cloudservices.size - 2
				system("su surfer -c 'firefox &'") # http://www.computerbild-cloud.de/' &") 
			elsif clouddrop.active == cloudservices.size - 1 # other WebDAV or CIFS
				if cloudserver.text.strip =~ /^http\:\/\// || cloudserver.text.strip =~ /^https\:\/\//
					mount_webdav(cloudserver.text.strip, clouduser.text.strip, cloudpass.text.strip)
					system("su surfer -c 'thunar /media/disk' &") 
				elsif cloudserver.text.strip =~ /^cifs\:\/\// || cloudserver.text.strip =~ /^smb\:\/\//
					mount_cifs(cloudserver.text.strip, clouduser.text.strip, cloudpass.text.strip)
					system("su surfer -c 'thunar /media/disk' &") 
				else
					TileHelpers.error_dialog @tl.get_translation("unknown_protocol")
				end
			#elsif clouddrop.active == 0 # Google
			#	if cloudtoken.text.strip.size < 1
			#		TileHelpers.error_dialog(@tl.get_translation("gdfs_token_missing"))
			#	else
			#		success = gdrivefs_mount(cloudtoken.text)
			#		TileHelpers.error_dialog(@tl.get_translation("gdfs_auth_failed")) unless success == true
			#	end
			#elsif clouddrop.active == 1 # Microsoft
			#	system("su surfer -c 'firefox https://onedrive.live.com/' &") 
			#	system("su surfer -c 'thunar /media/disk' &") 
			elsif clouddrop.active > 6 || clouddrop.active == 0 || clouddrop.active == 1
				system("su surfer -c 'firefox #{davurls[clouddrop.active]}' &") 
				system("su surfer -c 'thunar /media/disk' &") 
			else # predefined WebDAV
				mount_webdav(davurls[clouddrop.active], clouduser.text.strip, cloudpass.text.strip)
			end
		}
		fixed.signal_connect('show') {
			ffbutton.label = @tl.get_translation("openfilemanager")
			if clouddrop.active == cloudservices.size - 1
				cloudserver.sensitive = true
				cloudserver.visible = true
				serverlabel.visible = true
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = true }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			elsif clouddrop.active == cloudservices.size - 2
				ffbutton.label = @tl.get_translation("openfirefox")
				cloudserver.sensitive = false
				cloudserver.visible = false
				serverlabel.visible = false
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = false }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			#elsif clouddrop.active == 0
			#	cloudserver.sensitive = false
			#	cloudserver.visible = false
			#	serverlabel.visible = false
			#	[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = false }
			#	[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = true }
			elsif clouddrop.active > 6 || clouddrop.active == 0 || clouddrop.active == 1
				ffbutton.label = @tl.get_translation("openfirefox")
				cloudserver.sensitive = false
				cloudserver.visible = false
				serverlabel.visible = false
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = false }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			else
				cloudserver.sensitive = false
				cloudserver.visible = false
				serverlabel.visible = false
				[ clouduser, cloudpass, userlabel, passlabel ].each { |w| w.visible = true }
				[ tokenlabel, tokenbutton, cloudtoken ].each { |w| w.visible = false }
			end
			mount_all
			#	system("su surfer -c 'firefox &'") #  http://www.computerbild-cloud.de/' &") 
		}
		backbutton.signal_connect('button-release-event') { |x, y|
			if y.button == 1 
				extlayers.each { |k,v|v.hide_all }
				system("killall -15 firefox")
				sleep 2
				system("killall -9 firefox")
				TileHelpers.umount_all
				if TileHelpers.cloud_count > 0
					TileHelpers.umount_cloud if TileHelpers.yes_no_dialog(@tl.get_translation("umount_cloud")) == true 
				end
				extlayers["start"].show_all
			end
		}
		fixed.put(button1, 0, 0)
		fixed.put(deltext, 130, 0)
		fixed.put(clouddrop, 220, 108)
		fixed.put(droplabel, 130, 108)
		fixed.put(cloudserver, 220, 144)
		fixed.put(serverlabel, 130, 144)
		fixed.put(cloudtoken, 220, 144)
		fixed.put(tokenlabel, 130, 144)
		fixed.put(tokenbutton, 565, 144)
		fixed.put(clouduser, 220, 180)
		fixed.put(userlabel, 130, 180)
		fixed.put(cloudpass, 220, 216)
		fixed.put(passlabel, 130, 216)
		
		fixed.put(ffbutton, 495, 252)
		return fixed
	end
	
	def gdrivefs_mount(authtoken)
		if system("mountpoint -q /media/cloud/googledrive")
			system("nohup su surfer -c \"Thunar '/media/cloud/googledrive'\" &")
		end
		system("mkdir -p /media/cloud/googledrive")
		result = ` gdfstool auth -a /var/cache/googledrive '#{authtoken}' ` 
		system("gdfs -o allow_other /var/cache/googledrive /media/cloud/googledrive")
		if system("mountpoint -q /media/cloud/googledrive")
			system("nohup su surfer -c \"Thunar '/media/cloud/googledrive'\" &")
			return true 
		else
			return false
		end
	end
	
	def mount_webdav(davurl, user, password)
		protopath = davurl.split("://")
		hostfolder = protopath[1].split("/")
		if system("mountpoint \"/media/webdav/#{hostfolder[0]}/#{user.gsub("@", ".")}\"")
			TileHelpers.error_dialog(@tl.get_translation("already_mounted")) 
			return true
		else
			system("mkdir -p \"/media/webdav/#{hostfolder[0]}/#{user.gsub("@", ".")}\"")
		end
		system("echo -e '#{user}\n#{password}\ny' | LANG=en_GB.UTF-8 LANGUAGE=en mount.davfs -o rw,uid=1000,gid=1000,dir_mode=755,file_mode=644 \"#{davurl}\" \"/media/webdav/#{hostfolder[0]}/#{user.gsub("@", ".")}\"") 
		if system("mountpoint '/media/webdav/#{hostfolder[0]}/#{user.gsub("@", ".")}'")
			system("nohup su surfer -c \"Thunar '/media/webdav/#{hostfolder[0]}/#{user.gsub("@", ".")}'\" &")
			return true
		else
			TileHelpers.error_dialog(@tl.get_translation("error_mounting"))
			return false
		end
	end
	
	def mount_cifs(cifsurl, user, password)
		protopath = cifsurl.split("://")
		hostfolder = protopath[1].split("/")
		if system("mountpoint /media/cifs/#{hostfolder[0]}/#{hostfolder[1]}")
			TileHelpers.error_dialog(@tl.get_translation("already_mounted")) 
			return true
		else
			system("mkdir -p /media/cifs/#{hostfolder[0]}/#{hostfolder[1]}")
		end
		if user.strip == "" || password.strip == ""
			system("mount.cifs -o 'rw,uid=1000,gid=1000,file_mode=0644,dir_mode=0755,nounix,guest,iocharset=utf8' '//#{hostfolder[0]}/#{hostfolder[1]}' '/media/cifs/#{hostfolder[0]}/#{hostfolder[1]}'")
		else
			system("mount.cifs -o 'rw,uid=1000,gid=1000,file_mode=0644,dir_mode=0755,nounix,user=#{user},pass=#{password},iocharset=utf8' '//#{hostfolder[0]}/#{hostfolder[1]}' '/media/cifs/#{hostfolder[0]}/#{hostfolder[1]}'")
		end
		if system("mountpoint '/media/cifs/#{hostfolder[0]}/#{hostfolder[1]}'")
			system("nohup su surfer -c 'Thunar \"/media/cifs/#{hostfolder[0]}/#{hostfolder[1]}\"' &")
			return true
		else
			TileHelpers.error_dialog(@tl.get_translation("error_mounting"))
			return false
		end
	end
	
	def get_clonestart_layer(extlayers)
		
	end
	
	def reread_targetlist(combobox)
		100.downto(0) { |i| 
			begin
				combobox.remove_text(i) 
			rescue
			end
		}
		TileHelpers.umount_all
		drives = Array.new
		partitions = Array.new
		Dir.entries("/sys/block").each { |l|
			drives.push(MfsDiskDrive.new(l, false)) if l =~ /[a-z]$/ ||  l =~ /mmcblk[0-9]$/ ||  l =~ /mmcblk[0-9][0-9]$/
		}
		drives.each { |d|
			d.partitions.each  { |p|
				label = "#{d.vendor} #{d.model}"
				if d.usb == true
					label = label + " (USB) "
				else
					label = label + " (SATA/eSATA/IDE) "
				end
				label = label + "#{p.device} #{p.human_size}"
				pmnt = p.mount_point
				if ( p.fs =~ /vfat/ || p.fs =~ /ntfs/ || p.fs =~ /ext/ || p.fs =~ /btrfs/ ) && pmnt.nil?
					label = label + " #{p.fs}"
					partitions.push p.device
					combobox.append_text(label)
				end
			}
		}
		combobox.active = 0
		return drives, partitions
	end
	
	def mount_all(writeable_part=nil)
		begin
			bookmarks = File.new("/home/surfer/.gtk-bookmarks", "w")
		rescue
			bookmarks = File.new("/tmp/.gtk-bookmarks", "w")
		end
		drives = Array.new
		Dir.entries("/sys/block").each { |l|
			drives.push(MfsDiskDrive.new(l, false)) if l =~ /[a-z]$/ ||  l =~ /mmcblk[0-9]$/ ||  l =~ /mmcblk[0-9][0-9]$/
		}
		drives.each { |d|
			d.partitions.each { |p|
				$stderr.puts "#{p.device} vs. #{writeable_part}" 
				p.umount 
				if p.device.strip == writeable_part.to_s.strip
					$stderr.puts "Match!"
					system("mkdir -p /cobi/" + @tl.get_translation("backupdir")) 
					p.mount("rw", "/cobi/" + @tl.get_translation("backupdir"), 1000, 1000)
					bookmarks.write("file:///cobi/" + @tl.get_translation("backupdir") + "\n")
				else
					system("mkdir -p /media/disk/#{p.device}")
					p.mount("ro", "/media/disk/#{p.device}", 1000, 1000)
					bookmarks.write("file:///media/disk/#{p.device}\n")
				end
			}
		}
		bookmarks.close
		system("chown 1000:1000 /home/surfer/.gtk-bookmarks")
	end
	
end