vpac / install.vsh
381 lines · 350 sloc · 11.73 KB · 841315c100c81d9e6b14c4b55a25d4e3d12db762
Raw
1#!/usr/bin/env v
2
3import os
4import term
5
6// install.vsh sets vpac's config up for a new user: it asks a few questions,
7// then writes /etc/vpac.d/config.vile and the mirror file the config requires,
8// /etc/vpac.d/mirrors/<os>.vile. the config stays in /etc/vpac.d whatever the
9// answers: the pacman choice only picks where the db, cache, keys, hooks and
10// log live. VPAC_ETC writes the two files into another directory instead, a
11// trial that needs no root and makes no directory outside it. the binary is
12// built with `v . -o vpac`, which the installer's next steps name.
13
14const default_etc = '/etc/vpac.d'
15
16// distro is an os the config is written for: its name, which is also the rank
17// name (mirrors/<name>.vile defines mirrors-<name>), its repos, and the url its
18// mirrors start from, with the $repo and $arch placeholders left in it
19struct Distro {
20 name string
21 repos []string
22 src string
23 // lib32 is the distro's repo of 32-bit libraries, '' when it ships none:
24 // the shared mirror list serves it, the url's $repo picks the repo.
25 // cachyos builds a monorepo, so it has none and its question is skipped
26 lib32 string
27}
28
29fn distros() []Distro {
30 return [
31 Distro{
32 name: 'arch'
33 repos: ['core', 'extra']
34 src: 'https://geo.mirror.pkgbuild.com/\$repo/os/\$arch'
35 lib32: 'multilib'
36 },
37 Distro{
38 name: 'artix'
39 repos: ['system', 'world', 'galaxy']
40 src: 'https://mirror1.artixlinux.org/repos/\$repo/os/\$arch'
41 lib32: 'lib32'
42 },
43 Distro{
44 name: 'cachyos'
45 repos: ['cachyos']
46 src: 'https://mirror.cachyos.org/repo/\$arch/\$repo'
47 lib32: ''
48 },
49 Distro{
50 name: 'vinix'
51 },
52 ]
53}
54
55// paths are where vpac keeps its db, cache, keyring and hooks, and its log
56struct Paths {
57 db string
58 cache string
59 gpg string
60 hook string
61 log string
62}
63
64// pacman_paths are the directories pacman itself uses, which libalpm defaults
65// to. the local db is pacman's own, so vpac sees the packages pacman installed
66fn pacman_paths() Paths {
67 return Paths{
68 db: '/var/lib/pacman/'
69 cache: '/var/cache/pacman/pkg/'
70 gpg: '/etc/pacman.d/gnupg/'
71 hook: '/etc/pacman.d/hooks/'
72 log: '/var/log/pacman.log'
73 }
74}
75
76// own_paths are vpac's own, apart from pacman's. the db starts empty: it does
77// not know the packages pacman installed, and the keyring has no keys until
78// they are imported into it
79fn own_paths() Paths {
80 return Paths{
81 db: '/var/lib/vpac/'
82 cache: '/var/cache/vpac/pkg/'
83 gpg: '/etc/vpac.d/gnupg/'
84 hook: '/etc/vpac.d/hooks/'
85 log: '/var/log/vpac.log'
86 }
87}
88
89// answers are what the questions settled
90struct Answers {
91 distro string
92 aur bool
93 lib32 bool
94 root string
95 parallel int
96 color string
97 sandbox bool
98 arch string
99}
100
101fn main() {
102 run() or {
103 eprintln('install: ${err}')
104 exit(1)
105 }
106}
107
108fn run() ! {
109 trial := os.getenv('VPAC_ETC') != ''
110 etc := if trial { os.getenv('VPAC_ETC') } else { default_etc }
111 config := os.join_path(etc, 'config.vile')
112 mut replace := false
113 if os.exists(config) {
114 println('${config} exists.')
115 keep := ask_yes('replace it? the old file is kept as config.vile.old', false)!
116 if !keep {
117 println('kept ${config}: nothing changed')
118 return
119 }
120 replace = true
121 }
122
123 detected := detect_distro()
124 share_pacman := detected != 'vinix' && found('pacman')
125 && ask_yes("pacman is installed: keep vpac's db, cache, keys, hooks and log in pacman's directories?", true)!
126 distro := ask_choice('configure vpac for which os', distros().map(it.name), detected)!
127 d := distro_named(distro)
128 vinix := distro == 'vinix'
129 mut paths := own_paths()
130 if vinix {
131 paths = Paths{
132 ...paths
133 db: '/var/lib/vpac/db/'
134 }
135 println('Vinix uses /var/lib/vpac/root for payloads and /var/lib/vpac/db for its database.')
136 } else if share_pacman {
137 paths = pacman_paths()
138 } else {
139 println("using vpac's own directories and package database")
140 }
141
142 aur := !vinix && ask_yes('add the AUR as a pkgbuild repo', true)!
143 mut lib32 := false
144 if d.lib32 != '' {
145 // pacman.conf ships multilib commented out, so off is the default here too
146 lib32 = ask_yes('add the ${d.lib32} repo for 32-bit libraries', false)!
147 }
148 providers := ['doas', 'sudo', 'pkexec', 'su']
149 root := ask_choice('the command vpac gets root with', providers, root_default())!
150 parallel := ask_count('parallel downloads', 3, 1)!
151 color := ask_choice('color output', ['auto', 'always', 'never'], 'auto')!
152 if vinix {
153 println('Vinix lacks Landlock. Choose yes below to fetch packages and repository databases with the privileges of the vpac process.')
154 }
155 sandbox := ask_yes("turn off nspkg's download sandbox (pacman's DisableSandbox)", false)!
156
157 // the root command runs when the files are written to /etc: the same one
158 // the config names for vpac's own escalation
159 escalate := !trial && os.getuid() != 0
160 if escalate && !found(root) {
161 return error('${root} is not installed: install it, or run install.vsh as root')
162 }
163
164 a := Answers{
165 distro: distro
166 aur: aur
167 lib32: lib32
168 root: root
169 parallel: parallel
170 color: color
171 sandbox: sandbox
172 arch: os.uname().machine
173 }
174 mirror := os.join_path(etc, 'mirrors', '${d.name}.vile')
175 write_mirror := d.src != '' && !os.exists(mirror)
176
177 // the files are staged in a temp dir and then moved into place, so the
178 // root command only copies
179 stage := os.join_path(os.temp_dir(), 'vpac-install-${os.getpid()}')
180 os.mkdir_all(os.join_path(stage, 'mirrors'))!
181 defer {
182 os.rmdir_all(stage) or { eprintln('install: could not remove ${stage}: ${err}') }
183 }
184 staged_config := os.join_path(stage, 'config.vile')
185 staged_mirror := os.join_path(stage, 'mirrors', '${d.name}.vile')
186 os.write_file(staged_config, config_text(a, paths, d))!
187 if write_mirror {
188 os.write_file(staged_mirror, mirror_text(d))!
189 }
190
191 mut cmds := ['mkdir -p ${sh_quote(etc)}']
192 if write_mirror {
193 cmds << 'mkdir -p ${sh_quote(os.join_path(etc, 'mirrors'))}'
194 }
195 if !trial {
196 cmds << 'mkdir -p ${sh_quote(paths.db)} ${sh_quote(paths.cache)} ${sh_quote(paths.gpg)} ${sh_quote(paths.hook)}'
197 if vinix {
198 cmds << 'mkdir -p /var/lib/vpac/root'
199 }
200 }
201 if replace {
202 cmds << 'cp -f ${sh_quote(config)} ${sh_quote(config + '.old')}'
203 }
204 cmds << 'install -m 644 ${sh_quote(staged_config)} ${sh_quote(config)}'
205 if write_mirror {
206 cmds << 'install -m 644 ${sh_quote(staged_mirror)} ${sh_quote(mirror)}'
207 }
208 line := cmds.join(' && ')
209 argv := if escalate { root_argv(root, line) } else { ['sh', '-c', line] }
210 code := os.system_args(argv)
211 if code != 0 {
212 return error('writing ${config} failed (exit ${code}): fix the cause and run install.vsh again')
213 }
214
215 println('wrote ${config}')
216 if write_mirror {
217 println('wrote ${mirror}: one default url, which vpac k -w ranks')
218 } else if d.src != '' {
219 println('kept ${mirror}: it is already there')
220 }
221 println('')
222 println('next:')
223 build := if vinix { 'v -prod -cc gcc -o vpac .' } else { 'v . -o vpac' }
224 println(term.bold(' ${build}') + ' build vpac')
225 println(term.bold(' ln -sf $PWD/vpac /usr/local/bin') + ' symlink vpac to /usr/local/bin/vpac')
226 if vinix {
227 println(' Import and trust your package signing key in ${paths.gpg} before installing a signed local package.')
228 } else {
229 println(term.bold(' vpac k -w ') + ' rank the ${d.name} mirrors into ${mirror}')
230 }
231}
232
233// distro_named is the distro with the name, or the first one when none has it
234fn distro_named(name string) Distro {
235 for d in distros() {
236 if d.name == name {
237 return d
238 }
239 }
240 return distros()[0]
241}
242
243// detect_distro reads /etc/os-release the way the ranker does: the ID, then the
244// ID_LIKE, the first name that is one of the distros
245fn detect_distro() string {
246 text := os.read_file('/etc/os-release') or { return 'arch' }
247 mut id := ''
248 mut like := ''
249 for line in text.split_into_lines() {
250 if line.starts_with('ID=') {
251 id = line[3..].trim('"\'')
252 } else if line.starts_with('ID_LIKE=') {
253 like = line[8..].trim('"\'')
254 }
255 }
256 for candidate in [id, ...like.split(' ')] {
257 for d in distros() {
258 if d.name == candidate {
259 return candidate
260 }
261 }
262 }
263 return 'arch'
264}
265
266// found reports whether an executable is on the PATH
267fn found(exe string) bool {
268 path := os.find_abs_path_of_executable(exe) or { '' }
269 return path != ''
270}
271
272// root_default is the first root command on the machine, in the order the
273// installer prefers them
274fn root_default() string {
275 for p in ['doas', 'sudo', 'pkexec', 'su'] {
276 if found(p) {
277 return p
278 }
279 }
280 return 'su'
281}
282
283// root_argv is the command that runs one shell line as root through the root
284// command. su takes the line with -c, the others run it through sh
285fn root_argv(provider string, line string) []string {
286 if provider == 'su' {
287 return ['su', '-c', line]
288 }
289 return [provider, 'sh', '-c', line]
290}
291
292// sh_quote spells one word for a posix shell, in single quotes
293fn sh_quote(s string) string {
294 return "'" + s.replace("'", "'\\''") + "'"
295}
296
297// read_answer reads one line off stdin. the end of input is an error and not an
298// answer, so a run with stdin closed stops before it writes anything
299fn read_answer(prompt string) !string {
300 line := os.input_opt(prompt) or {
301 return error('stdin closed before the questions were answered: nothing was written')
302 }
303 return line.trim_space()
304}
305
306// ask reads one answer: the default when it is left empty
307fn ask(question string, default string) !string {
308 suffix := if default == '' { '' } else { ' [${default}]' }
309 answer := read_answer('${question}${suffix}: ')!
310 return if answer == '' { default } else { answer }
311}
312
313fn ask_yes(question string, default bool) !bool {
314 hint := if default { 'Y/n' } else { 'y/N' }
315 for {
316 raw := read_answer('${question} [${hint}]: ')!
317 match raw.to_lower() {
318 '' { return default }
319 'y', 'yes' { return true }
320 'n', 'no' { return false }
321 else { println('answer y or n') }
322 }
323 }
324 return default
325}
326
327fn ask_choice(question string, choices []string, default string) !string {
328 for {
329 answer := ask('${question} (${choices.join(' / ')})', default)!
330 if answer in choices {
331 return answer
332 }
333 println('answer one of: ${choices.join(', ')}')
334 }
335 return default
336}
337
338fn ask_count(question string, default int, min int) !int {
339 for {
340 answer := ask(question, '${default}')!
341 if answer.len > 0 && answer.bytes().all(it.is_digit()) && answer.int() >= min {
342 return answer.int()
343 }
344 println('answer a whole number, ${min} or more')
345 }
346 return default
347}
348
349// The mirror file supplies the servers shared by the distro's repositories.
350fn config_text(a Answers, p Paths, d Distro) string {
351 mut repos := []string{}
352 for name in d.repos {
353 repos << 'sync-repo("${name}", mirrors-${d.name})'
354 }
355 if a.lib32 { repos << 'sync-repo("${d.lib32}", mirrors-${d.name})' }
356 if a.aur { repos << 'pkgbuild-repo("aur", "https://aur.archlinux.org")' }
357 vinix := d.name == 'vinix'
358 mut lines := ['; vpac configuration']
359 if d.src != '' { lines << 'load("mirrors/${d.name}.vile")' }
360 root := if vinix { '/var/lib/vpac/root/' } else { '/' }
361 hold := if vinix { '[]' } else { '["pacman", "glibc"]' }
362 user := if vinix { 'nobody' } else { 'alpm' }
363 lines << ['', 'path-root = "${root}"', 'path-db = "${p.db}"', 'path-log = "${p.log}"',
364 'path-gpg = "${p.gpg}"', 'path-cache = ["${p.cache}"]', 'path-hook = ["${p.hook}"]', '',
365 'pkg-arch = "${a.arch}"', 'pkg-hold = ${hold}', '', 'network-connections = ${a.parallel}',
366 'network-protocols = ["https"]', 'network-user = "${user}"']
367 if a.sandbox { lines << 'network-disable-sandbox = true' }
368 if vinix {
369 lines << 'network-siglevel = ["package", "database"]'
370 lines << r'pkgbuild-makepkg = "PACMAN=/opt/vpac/fakeroot/bin/vpac-query PATH=/opt/vpac/fakeroot/bin:$PATH makepkg -f --sign"'
371 }
372 lines << ['', 'options-root = "${a.root}"', 'options-color = "${a.color}"', '']
373 if repos.len > 0 {
374 lines << 'repositories = list(' + '\n ' + repos.join(',\n ') + '\n)'
375 }
376 return lines.join('\n') + '\n'
377}
378
379fn mirror_text(d Distro) string {
380 return '; mirrors for ${d.name}, the default until vpac k -w ranks them\nmirrors-${d.name} := ["${d.src}"]\n'
381}
382