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