vpac / install.vsh
374 lines · 338 sloc · 10.95 KB · 681562d743ca332e867e20a5d9a74f9d33e74e96
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.lip and the mirror file the config requires,
8// /etc/vpac.d/mirrors/<os>.lip. 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>.lip 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 ]
50}
51
52// paths are where vpac keeps its db, cache, keyring and hooks, and its log
53struct Paths {
54 db string
55 cache string
56 gpg string
57 hook string
58 log string
59}
60
61// pacman_paths are the directories pacman itself uses, which libalpm defaults
62// to. the local db is pacman's own, so vpac sees the packages pacman installed
63fn pacman_paths() Paths {
64 return Paths{
65 db: '/var/lib/pacman/'
66 cache: '/var/cache/pacman/pkg/'
67 gpg: '/etc/pacman.d/gnupg/'
68 hook: '/etc/pacman.d/hooks/'
69 log: '/var/log/pacman.log'
70 }
71}
72
73// own_paths are vpac's own, apart from pacman's. the db starts empty: it does
74// not know the packages pacman installed, and the keyring has no keys until
75// they are imported into it
76fn own_paths() Paths {
77 return Paths{
78 db: '/var/lib/vpac/'
79 cache: '/var/cache/vpac/pkg/'
80 gpg: '/etc/vpac.d/gnupg/'
81 hook: '/etc/vpac.d/hooks/'
82 log: '/var/log/vpac.log'
83 }
84}
85
86// answers are what the questions settled
87struct Answers {
88 distro string
89 aur bool
90 lib32 bool
91 root string
92 parallel int
93 color string
94 sandbox bool
95 arch string
96}
97
98fn main() {
99 run() or {
100 eprintln('install: ${err}')
101 exit(1)
102 }
103}
104
105fn run() ! {
106 trial := os.getenv('VPAC_ETC') != ''
107 etc := if trial { os.getenv('VPAC_ETC') } else { default_etc }
108 config := os.join_path(etc, 'config.lip')
109 mut replace := false
110 if os.exists(config) {
111 println('${config} exists.')
112 keep := ask_yes('replace it? the old file is kept as config.lip.old', false)!
113 if !keep {
114 println('kept ${config}: nothing changed')
115 return
116 }
117 replace = true
118 }
119
120 mut paths := own_paths()
121 if found('pacman') {
122 if ask_yes("pacman is installed: keep vpac's db, cache, keys, hooks and log in pacman's directories?", true)! {
123 paths = pacman_paths()
124 } else {
125 println("note: vpac's own db starts empty and does not see the packages pacman installed")
126 }
127 } else {
128 println("pacman is not installed: vpac links libalpm, which the pacman package ships, so install pacman before vpac can run. the config uses vpac's own directories")
129 }
130
131 distro := ask_choice('mirrors for which os', distros().map(it.name), detect_distro())!
132 d := distro_named(distro)
133 aur := ask_yes('add the AUR as a pkgbuild repo', true)!
134 mut lib32 := false
135 if d.lib32 != '' {
136 // pacman.conf ships multilib commented out, so off is the default here too
137 lib32 = ask_yes('add the ${d.lib32} repo for 32-bit libraries', false)!
138 }
139 providers := ['doas', 'sudo', 'pkexec', 'su']
140 root := ask_choice('the command vpac gets root with', providers, root_default())!
141 parallel := ask_count('parallel downloads', 3, 1)!
142 color := ask_choice('color output', ['auto', 'always', 'never'], 'auto')!
143 sandbox := ask_yes("turn libalpm's sandbox off for downloads and extraction (pacman's DisableSandbox)", false)!
144
145 // the root command runs when the files are written to /etc: the same one
146 // the config names for vpac's own escalation
147 escalate := !trial && os.getuid() != 0
148 if escalate && !found(root) {
149 return error('${root} is not installed: install it, or run install.vsh as root')
150 }
151
152 a := Answers{
153 distro: distro
154 aur: aur
155 lib32: lib32
156 root: root
157 parallel: parallel
158 color: color
159 sandbox: sandbox
160 arch: os.uname().machine
161 }
162 mirror := os.join_path(etc, 'mirrors', '${d.name}.lip')
163 write_mirror := !os.exists(mirror)
164
165 // the files are staged in a temp dir and then moved into place, so the
166 // root command only copies
167 stage := os.join_path(os.temp_dir(), 'vpac-install-${os.getpid()}')
168 os.mkdir_all(os.join_path(stage, 'mirrors'))!
169 defer {
170 os.rmdir_all(stage) or { eprintln('install: could not remove ${stage}: ${err}') }
171 }
172 staged_config := os.join_path(stage, 'config.lip')
173 staged_mirror := os.join_path(stage, 'mirrors', '${d.name}.lip')
174 os.write_file(staged_config, config_text(a, paths, d))!
175 os.write_file(staged_mirror, mirror_text(d))!
176
177 mut cmds := ['mkdir -p ${sh_quote(etc)} ${sh_quote(os.join_path(etc, 'mirrors'))}']
178 if !trial {
179 cmds << 'mkdir -p ${sh_quote(paths.db)} ${sh_quote(paths.cache)} ${sh_quote(paths.gpg)} ${sh_quote(paths.hook)}'
180 }
181 if replace {
182 cmds << 'cp -f ${sh_quote(config)} ${sh_quote(config + '.old')}'
183 }
184 cmds << 'install -m 644 ${sh_quote(staged_config)} ${sh_quote(config)}'
185 if write_mirror {
186 cmds << 'install -m 644 ${sh_quote(staged_mirror)} ${sh_quote(mirror)}'
187 }
188 line := cmds.join(' && ')
189 argv := if escalate { root_argv(root, line) } else { ['sh', '-c', line] }
190 code := os.system_args(argv)
191 if code != 0 {
192 return error('writing ${config} failed (exit ${code}): fix the cause and run install.vsh again')
193 }
194
195 println('wrote ${config}')
196 if write_mirror {
197 println('wrote ${mirror}: one default url, which vpac k -w ranks')
198 } else {
199 println('kept ${mirror}: it is already there')
200 }
201 println('')
202 println('next:')
203 println(term.bold(' v . -o vpac ') + ' build vpac')
204 println(term.bold(' ln -sf $PWD/vpac /usr/local/bin') + ' symlink vpac to /usr/local/bin/vpac')
205 println(term.bold(' vpac k -w ') + ' rank the ${d.name} mirrors into ${mirror}')
206}
207
208// distro_named is the distro with the name, or the first one when none has it
209fn distro_named(name string) Distro {
210 for d in distros() {
211 if d.name == name {
212 return d
213 }
214 }
215 return distros()[0]
216}
217
218// detect_distro reads /etc/os-release the way the ranker does: the ID, then the
219// ID_LIKE, the first name that is one of the distros
220fn detect_distro() string {
221 text := os.read_file('/etc/os-release') or { return 'arch' }
222 mut id := ''
223 mut like := ''
224 for line in text.split_into_lines() {
225 if line.starts_with('ID=') {
226 id = line[3..].trim('"\'')
227 } else if line.starts_with('ID_LIKE=') {
228 like = line[8..].trim('"\'')
229 }
230 }
231 for candidate in [id, ...like.split(' ')] {
232 for d in distros() {
233 if d.name == candidate {
234 return candidate
235 }
236 }
237 }
238 return 'arch'
239}
240
241// found reports whether an executable is on the PATH
242fn found(exe string) bool {
243 path := os.find_abs_path_of_executable(exe) or { '' }
244 return path != ''
245}
246
247// root_default is the first root command on the machine, in the order the
248// installer prefers them
249fn root_default() string {
250 for p in ['doas', 'sudo', 'pkexec', 'su'] {
251 if found(p) {
252 return p
253 }
254 }
255 return 'su'
256}
257
258// root_argv is the command that runs one shell line as root through the root
259// command. su takes the line with -c, the others run it through sh
260fn root_argv(provider string, line string) []string {
261 if provider == 'su' {
262 return ['su', '-c', line]
263 }
264 return [provider, 'sh', '-c', line]
265}
266
267// sh_quote spells one word for a posix shell, in single quotes
268fn sh_quote(s string) string {
269 return "'" + s.replace("'", "'\\''") + "'"
270}
271
272// read_answer reads one line off stdin. the end of input is an error and not an
273// answer, so a run with stdin closed stops before it writes anything
274fn read_answer(prompt string) !string {
275 line := os.input_opt(prompt) or {
276 return error('stdin closed before the questions were answered: nothing was written')
277 }
278 return line.trim_space()
279}
280
281// ask reads one answer: the default when it is left empty
282fn ask(question string, default string) !string {
283 suffix := if default == '' { '' } else { ' [${default}]' }
284 answer := read_answer('${question}${suffix}: ')!
285 return if answer == '' { default } else { answer }
286}
287
288fn ask_yes(question string, default bool) !bool {
289 hint := if default { 'Y/n' } else { 'y/N' }
290 for {
291 raw := read_answer('${question} [${hint}]: ')!
292 match raw.to_lower() {
293 '' { return default }
294 'y', 'yes' { return true }
295 'n', 'no' { return false }
296 else { println('answer y or n') }
297 }
298 }
299 return default
300}
301
302fn ask_choice(question string, choices []string, default string) !string {
303 for {
304 answer := ask('${question} (${choices.join(' / ')})', default)!
305 if answer in choices {
306 return answer
307 }
308 println('answer one of: ${choices.join(', ')}')
309 }
310 return default
311}
312
313fn ask_count(question string, default int, min int) !int {
314 for {
315 answer := ask(question, '${default}')!
316 if answer.len > 0 && answer.bytes().all(it.is_digit()) && answer.int() >= min {
317 return answer.int()
318 }
319 println('answer a whole number, ${min} or more')
320 }
321 return default
322}
323
324// config_text is the one config file: every form a user is likely to want,
325// with the mirror file of the distro required beside it
326fn config_text(a Answers, p Paths, d Distro) string {
327 mut repos := []string{}
328 for name in d.repos {
329 repos << '(repo\n :name "${name}"\n :src mirrors-${d.name})'
330 }
331 if a.lib32 {
332 repos << '(repo\n :name "${d.lib32}"\n :src mirrors-${d.name})'
333 }
334 if a.aur {
335 repos << '(repo\n :name "aur"\n :type "pkgbuild"\n :src "https://aur.archlinux.org")'
336 }
337 return '; vpac config, written by install.vsh: edit it by hand, or run install.vsh again.
338(require "mirrors/${d.name}.lip")
339
340(path
341 :root "/"
342 :db "${p.db}"
343 :log "${p.log}"
344 :gpg "${p.gpg}"
345 :cache ["${p.cache}"]
346 :hook ["${p.hook}"])
347
348(pkg
349 :arch "${a.arch}"
350 :hold ["pacman" "glibc"])
351
352(network
353 :parallel ${a.parallel}
354 :protocols ["https"]
355 :user "alpm"' +
356 if a.sandbox { ' :disable-sandbox true' } else { '' } +
357 ')
358
359(options
360 :root "${a.root}"
361 :color "${a.color}")
362
363${repos.join('\n\n')}
364'
365}
366
367// mirror_text is a mirror file as rank writes one: mirrors-<os> is defined
368// and holds the urls, here the distro's one url until the ranking replaces it
369fn mirror_text(d Distro) string {
370 return '; mirrors for ${d.name}, the default until vpac k -w ranks them
371(unless (defined? mirrors-${d.name}) (define mirrors-${d.name} []))
372(array-append! mirrors-${d.name} ["${d.src}"])
373'
374}
375