aboutsummaryrefslogtreecommitdiff
path: root/scripts/.scripts/write_on_disk.rb
blob: dc6f280c9ae3127918eeced9ee9146258650d0df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    #!/usr/bin/env ruby
    require 'dbus'
    require 'awesome_print'
    require 'filesize'
    require 'colorize'
     
    loop = DBus::Main.new
    bus = DBus::SystemBus.instance
     
    udisk2   = bus['org.freedesktop.UDisks2']
    device = nil
     
    EXPECTED_INTERFACES = %w[org.freedesktop.UDisks2.PartitionTable org.freedesktop.UDisks2.Block]
     
    manager = udisk2['/org/freedesktop/UDisks2']['org.freedesktop.DBus.ObjectManager']
    manager.on_signal 'InterfacesAdded' do |path|
    	interfaces = udisk2[path].interfaces
    	next unless (EXPECTED_INTERFACES - interfaces).empty?
    	block = udisk2[path]['org.freedesktop.UDisks2.Block']
     
    	path = path.split('/').last
     
    	drive = block['Drive']
    	drive = udisk2[drive]['org.freedesktop.UDisks2.Drive']
    	id = drive['Id']
    	size = Filesize.new drive['Size']
     
    	device = { path: path, id: id, size: size }
     
    	loop.quit
    end
     
    iso = ARGV.first
    size = File.size iso
    puts "#{'Plug a drive'.colorize :red} to begin to write #{iso.colorize :green} [#{Filesize.new(size).pretty.colorize :yellow}]"
     
    loop << bus
    loop.run
     
    print "Erase #{device[:id].colorize :red} [#{device[:size].pretty.colorize :yellow}]? [y/N] "
    answer = STDIN.gets.chomp
     
    exit -1 unless answer.downcase == 'y'
    device = File.join '/dev/', device[:path]
    current = 0
    chunk = Filesize.from('4MiB').to_i
     
    File.open iso, 'rb' do |iso|
    	File.open device, 'wb' do |device|
    		while read = iso.read(chunk) do
    			current += read.size
    			device.write read
    			print "\r[%6.2f%%] %d/%d" % [current.to_f / size * 100, current, size]
    		end
    		puts
    		puts 'Finalizing...'.colorize :yellow
    	end
    end
    puts 'Done!'.colorize :green