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