/
get_image.escript
executable file
·95 lines (78 loc) · 2.69 KB
/
get_image.escript
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env escript
%%%
%%% Download a test OS image and create the configuration
%%%
%% Environment Variables
%%
%% VERT_QEMU_BIN : path to the qemu binary (default: /usr/bin/kvm)
%% VERT_BRIDGE_INTERFACE : bridge interface (default: user networking)
main(_) ->
inets:start(),
ssl:start(),
URI = "http://downloads.openwrt.org/backfire/10.03.1/x86_generic/openwrt-x86-generic-combined-ext2.img.gz",
File = "priv/" ++ filename:rootname(filename:basename(URI)),
Cfg = "priv/example.xml",
download(URI, File),
config(Cfg, File).
download(URI, File) ->
io:format("Checking download test image ...~n"),
case file:read_file_info(File) of
{ok, _} ->
ok;
{error, enoent} ->
io:format("Downloading image: ~p -> ~p~n", [URI, File]),
{ok, _} = httpc:request(get, {URI, []}, [], [{stream, File}]),
os:cmd("gunzip " ++ File ++ ".gz")
end.
config(Cfg, File) ->
io:format("Checking configuration...~n"),
case file:read_file_info(Cfg) of
{ok, _} ->
ok;
{error, enoent} ->
Dist = Cfg ++ ".dist",
io:format("Creating config: ~p -> ~p~n", [Dist, Cfg]),
{ok, Dir} = file:get_cwd(),
{ok, Bin} = file:read_file(Dist),
Qemu = get_qemu_path(),
Interface = get_interface(),
Bin1 = lists:foldl(fun({Replace, With}, Buf) ->
io:format("~s: ~s = ~s~n", [Cfg, Replace, With]),
re:replace(Buf, Replace, With, [{return, binary}])
end,
Bin,
[
{"@PATH@", Dir ++ "/" ++ File},
{"@QEMU@", Qemu},
{"@INTERFACE@", Interface}
]),
ok = file:write_file(Cfg, Bin1)
end.
get_qemu_path() ->
Qemu = os:getenv("VERT_QEMU_BIN"),
case Qemu of
false -> "/usr/bin/kvm";
_ -> Qemu
end.
get_interface() ->
Bridge = os:getenv("VERT_BRIDGE_INTERFACE"),
interface(Bridge).
interface(false) ->
io_lib:format(
"<interface type='user'>
<mac address='~s'/>
</interface>", [macaddr()]
);
interface(Bridge) ->
io_lib:format(
"<interface type='bridge'>
<mac address='~s'/>
<source bridge='~s'/>
<model type='virtio'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>", [macaddr(), Bridge]
).
macaddr() ->
"52:54:00:" ++ lists:flatten(string:join(
[ io_lib:format("~.16B", [N]) || <<N>> <= crypto:rand_bytes(3) ],
":")).