aboutsummaryrefslogtreecommitdiffstats
path: root/roles/vmm/files/init_vm_alpine.py
blob: 126a0bc16a4f1bc17c5d1f50c040a5608db7bf48 (plain) (blame)
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
#!/bin/python3

import serial
import subprocess
import sys
import os

from serial_macro import *

USAGE = f"USAGE: {sys.argv[0]} vm_guest gate ip mask ssh_key"

def init_network():
    send_cmds(ser, [
        [1, "setup-interfaces"],
        [1, ""],
        [1, f"{IP}"],
        [1, f"{MASK}"],
        [1, f"{GATE}"],
        [1, "no"],
        [1, "ifdown -a"],
        [10, "ifup -a"],
        [1, "rc-update add networking"]
    ])


def init_dns():
    send_cmds(ser, [
        [1, f"setup-dns"],
        [1, ""],
        [1, f"{DNS}"],
    ])


def init_disk():
    send_cmds(ser, [
        [10, "apk add e2fsprogs sfdisk syslinux"],
        [1, "setup-disk"],
        [1, ""],
        [10, "sys"],
        [30, "y"],
    ])


def init_ssh():
    send_cmds(ser, [
        [5, "apk add openssh"],
        [1, "mkdir /root/.ssh"],
        [1, f"echo '{SSHKEY}' > /root/.ssh/authorized_keys"],
        [1, f"echo 'PermitRootLogin yes' >> /etc/ssh/sshd_config"],
        [1, "/etc/init.d/sshd restart"],
        [1, "rc-update add sshd"]
    ])

def init_packages():
    send_cmds(ser, [
        [1, "echo https://mirror.ungleich.ch/mirror/packages/alpine/latest-stable/main/ > /etc/apk/repositories "],
        [5, "apk update"]
    ])


def main():

    global ser
    global IP
    global GATE
    global MASK
    global DNS
    global SSHKEY

    COM = "/dev/"
    BAUD = 115200
    TIMEOUT = 1

    if len(sys.argv) != 7:
        sys.stderr.write(USAGE)
        sys.exit(1)

    GUEST = "vm-tmp"
    HOST = sys.argv[1]

    cmd = f"vmctl show | grep {GUEST} | tr -s ' ' | cut -d ' ' -f7"
    _buffer = subprocess.check_output(cmd, shell=True).decode().rstrip()
    print(_buffer)

    if _buffer == "":
        sys.exit(1)
    COM += _buffer

    IP = sys.argv[2]
    GATE = sys.argv[3]
    MASK = sys.argv[4]
    DNS = sys.argv[5]
    SSHKEY = sys.argv[6]

    ser = serial.Serial(COM, BAUD, timeout=TIMEOUT)
    send_cmd(ser, 1, "root")
    # first boot :: live
    init_network()
    init_dns()
    init_packages()
    init_disk()
    send_cmd(ser, 70, "reboot")
    ser.close()

    ser = serial.Serial(COM, BAUD, timeout=TIMEOUT)
    send_cmd(ser, 1, "root")
    # second boot :: disk
    init_network()
    init_dns()
    init_ssh()
    init_packages()
    ser.close()


if __name__ == "__main__":
    main()
remember that computers suck.