forked from nolim1t/pi-init3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
388 lines (316 loc) · 8.46 KB
/
main.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// +build linux
/* pi-init3
*
* A shim to drop onto a Raspberry Pi to write some files to its root
* filesystem before giving way to the real /sbin/init. Its goal is simply
* to allow you to customise a RPi by dropping files into that FAT32 /boot
* partition, as opposed to either 1) booting it and manually setting it up, or
* 2) having to mount the root partition, which Windows & Mac users can't easily
* do.
*
* Cross-compile for Raspberry Pi:
* go mod sync
* GOOS=linux GOARCH=arm GOARM=5 go build pi-init3
*/
package main
import (
"fmt"
"golang.org/x/sys/unix"
"io"
"io/ioutil"
"os"
"strings"
"syscall"
"time"
//"os/exec"
)
var (
exists = []syscall.Errno{syscall.EEXIST}
serviceInstallPath = "/lib/systemd/system/"
serviceEnablePath = "/etc/systemd/system/multi-user.target.wants/"
)
func checkFatalAllowed(desc string, err error, allowedErrnos []syscall.Errno) {
if err == nil {
return
}
if errNo, ok := err.(syscall.Errno); ok {
for _, b := range allowedErrnos {
if b == errNo {
return
}
}
}
fmt.Println("error " + desc + ":" + err.Error())
time.Sleep(10 * time.Second)
unix.Exit(1)
}
func checkFatal(desc string, err error) {
checkFatalAllowed(desc, err, []syscall.Errno{})
}
// from https://gist.github.com/elazarl/5507969
func cp(dst, src string) error {
s, err := os.Open(src)
if err != nil {
return err
}
// no need to check errors on read only file, we already got everything
// we need from the filesystem, so nothing can go wrong now.
defer s.Close()
d, err := os.Create(dst)
if err != nil {
return err
}
if _, err := io.Copy(d, s); err != nil {
d.Close()
return err
}
return d.Close()
}
func createFile(filename string, permissions os.FileMode, contents string) {
ioutil.WriteFile(filename, []byte(strings.TrimLeft(contents, "\r\n\t ")), permissions)
}
func createService(name, contents string) error {
src := serviceInstallPath + name + ".service"
dst := serviceEnablePath + name + ".service"
createFile(src, 0644, contents)
return os.Symlink(src, dst)
}
func remountRw() {
checkFatal(
"changing directory",
unix.Chdir("/"),
)
checkFatal(
"remount rw",
unix.Mount("/", "/", "vfat", syscall.MS_REMOUNT, ""),
)
}
func mountTmp() {
checkFatalAllowed(
"making tmp",
unix.Mkdir("tmp", 0770),
exists,
)
checkFatal(
"mounting tmp",
unix.Mount("", "tmp", "tmpfs", 0, ""),
)
}
func mountRoot() {
checkFatalAllowed(
"making new_root",
unix.Mkdir("new_root", 0770),
exists,
)
checkFatal(
"create device node",
unix.Mknod("tmp/mmcblk0p2", 0660|syscall.S_IFBLK, 179<<8|2),
)
checkFatal(
"mounting real root",
unix.Mount("tmp/mmcblk0p2", "new_root", "ext4", 0, ""),
)
}
func adjustMounts() {
// new_root becomes root FS & current root FS moves to new_root/boot
checkFatal(
"pivoting",
unix.PivotRoot("new_root", "new_root/boot"),
)
// See: https://linux.die.net/man/8/pivot_root
checkFatal(
"unmounting /boot/tmp",
unix.Unmount("/boot/tmp", 0),
)
checkFatal(
"removing /boot/new_root",
os.Remove("/boot/new_root"),
)
checkFatal(
"removing /boot/tmp",
os.Remove("/boot/tmp"),
)
checkFatal(
"changing into boot directory",
unix.Chdir("/boot"),
)
}
func replaceCmdline() {
//fixpartuuid()
checkFatal(
"renaming cmdline.txt to cmdline.txt.pi-init3",
unix.Rename("/boot/cmdline.txt", "/boot/cmdline.txt.pi-init3"),
)
checkFatal(
"renaming cmdline.txt.orig to cmdline.txt",
unix.Rename("/boot/cmdline.txt.orig", "/boot/cmdline.txt"),
)
}
/*func fixpartuuid() {
_, err := exec.Command("/bin/sh", "/boot/pi-init3_fix_partuuid.sh").Output()
if err != nil {
fmt.Println("error fixpartuuid:" + err.Error())
}
// Try one. Print disk info
/*
package main
import (
"github.com/shirou/gopsutil/disk"
"fmt"
"strconv"
)
func main() {
parts, err := disk.Partitions(false)
check(err)
//var usage []*disk.UsageStat
for _, part := range parts {
//u, err := disk.Usage(part.Mountpoint)
//_, err := disk.Usage(part.Mountpoint)
//check(err)
//usage = append(usage, u)
//printUsage(u)
fmt.Println(part.Opts)
}
}
func printUsage(u *disk.UsageStat) {
fmt.Println(u.Path + "\t" + strconv.FormatFloat(u.UsedPercent, 'f', 2, 64) + "% full.")
fmt.Println("Total: " + strconv.FormatUint(u.Total/1024/1024/1024, 10) + " GiB")
fmt.Println("Free: " + strconv.FormatUint(u.Free /1024/1024/1024, 10) + " GiB")
fmt.Println("Used: " + strconv.FormatUint(u.Used /1024/1024/1024, 10) + " GiB")
}
func check(err error) {
if err != nil {
panic(err)
}
}
* /
Try two
/*
package main
import (
"fmt"
"github.com/shirou/gopsutil/disk"
//"io/ioutil"
//"strings"
//"github.com/jaypipes/ghw"
)
func fixpartuuid() {
// Print disk serial number
fmt.Printf("output is %s\n", disk.GetDiskSerialNumber("/dev/mmcblk0p1"))
// Replace smth in file
/*path := "/root/go/qwe.qwe"
read, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
fmt.Println(string(read))
fmt.Println(path)
//newContents := strings.Replace(string(read), "qqq", "new", -1)
newContents := strings.Replace(string(read), "new", string(disk.GetDiskSerialNumber('/dev/mmcblk0p1')), -1)
fmt.Println(newContents)
err = ioutil.WriteFile(path, []byte(newContents), 0)
if err != nil {
panic(err)
}* /
// List info by partition
/*block, err := ghw.Block()
if err != nil {
fmt.Printf("Error getting block storage info: %v", err)
}
fmt.Printf("%v\n", block)
for _, disk := range block.Disks {
fmt.Printf(" %v\n", disk)
for _, part := range disk.Partitions {
fmt.Printf(" %v\n", part)
}
}* /
}
func main() {
fixpartuuid()
}
* /
}*/
func reboot() {
unix.Sync()
unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
}
func customize() {
checkFatal(
"changing into boot directory",
unix.Chdir("/boot"),
)
checkFatalAllowed(
"making on-boot.d",
unix.Mkdir("on-boot.d", 0770),
exists,
)
checkFatalAllowed(
"making run-once.d",
unix.Mkdir("run-once.d", 0770),
exists,
)
checkFatalAllowed(
"making run-once.d/completed",
unix.Mkdir("run-once.d/completed", 0770),
exists,
)
createFile("/usr/local/sbin/pi-init3-run-parts.sh", 0744, `
#!/bin/bash
# Prevent *.sh from returning itself if there are no matches
shopt -s nullglob
# Allow lazily named scripts to work
for script in /boot/run-once*; do
if [[ -f $script ]]; then
$script
status=$?
if $(exit $status); then
mv $script /boot/run-once.d/completed/
fi
fi
done
#Make executable
chmod +x -R --quiet /boot/run-once.d
# Run every run-once script
run-parts --verbose --exit-on-error /boot/run-once.d 2>/tmp/completed
sed -i '/^run-parts: executing/!d;s/^run-parts: executing *//' /tmp/completed
# Pop last script off the list if run-parts exited on an error
status=$?
if ! $(exit $status); then
sed -i '$d' /tmp/completed
fi
# Move completed scripts
while read script; do
mv $script /boot/run-once.d/completed/
done < /tmp/completed
#Make executable
chmod +x -R --quiet /boot/on-boot.d
# Run every on-boot script
run-parts /boot/on-boot.d
`)
createService("pi-init3", `
[Unit]
Description=Run user provided scripts on boot
ConditionPathExists=/usr/local/sbin/pi-init3-run-parts.sh
After=network-online.target raspi-config.service
[Service]
ExecStart=/usr/local/sbin/pi-init3-run-parts.sh
Type=oneshot
TimeoutSec=600
[Install]
WantedBy=multi-user.target
`)
}
func main() {
remountRw()
mountTmp()
mountRoot()
adjustMounts()
customize()
replaceCmdline()
/*
checkFatal(
"exec real init",
syscall.Exec("/sbin/init", os.Args, nil))
*/
reboot()
}