blob: 05c04b09450920a5f34748848bc9a6e1d507f087 [file] [log] [blame]
Piotr Dobrowolskia01905a2021-10-16 18:22:46 +02001#!/usr/bin/env nix-shell
2#!nix-shell -i python3 -p grub2 rsync utillinux shadow utillinux e2fsprogs
3from subprocess import run
4from pathlib import Path
5from tempfile import TemporaryDirectory
6import argparse
7import json
8import os
9import sys
10import time
11
12root_device = Path('/dev/disk/by-id/ata-Crucial_CT250MX200SSD1_1537108FC44F')
13bios_boot_part_type = '21686148-6449-6E6F-744E-656564454649'
14config_dir = Path(__file__).parent.parent.absolute()
15
16if os.getlogin() != 'root':
17 print("ERROR: must be run as root", file=sys.stderr)
18 sys.exit(1)
19
20if not root_device.exists():
21 print(f"ERROR: {root_device} not found", file=sys.stderr)
22 sys.exit(1)
23
24print(f"WARNING: this script will WIPE all data on {root_device}")
25if input('Write "Yes" to continue:') != 'Yes':
26 sys.exit(1)
27
28with TemporaryDirectory() as tmp_path:
29 tmp = Path(tmp_path)
30 print(f"Created temporary directory {tmp}")
31
32 parts = (
33 'label: gpt\n'
34 f'name=grub start=2MiB size=10MiB type={bios_boot_part_type}\n'
35 'name=root size=100GiB\n'
36 )
37 run(['sfdisk', root_device], input=parts.encode())
38
39 parts_info = json.loads(run(['sfdisk', '--json', root_device], capture_output=True, check=True).stdout.decode())
40 root_part = Path(parts_info["partitiontable"]["partitions"][1]['node']).resolve()
41
42 for i in range(40):
43 if root_part.exists():
44 break
45 time.sleep(0.2)
46 else:
47 print(f"ERROR: create partition not exists: {root_part}", file=sys.stderr)
48 sys.exit(1)
49
50 run(['mkfs.ext4', root_part])
51
52 root = tmp.joinpath('root')
53 root.mkdir()
54
55 try:
56 run(['mount', root_part, root], check=True)
57
58 run(['mkdir', '-p', root.joinpath('etc', 'nixos')], check=True)
59 run(['rsync', '-r', '--progress', f'{config_dir!s}/', root.joinpath('etc', 'nixos')], check=True)
60
61 root_uuid = parts_info["partitiontable"]["partitions"][1]['uuid'].lower()
62 root.joinpath('etc', 'nixos', 'hw.json').write_text(json.dumps({
63 "rootUUID": f'{root_uuid}',
64 }))
65
66 run(['nixos-install', '--no-root-passwd', '--root', root], check=True)
67 run(['grub-install', f'--root-directory={root!s}', f'--boot-directory={root.joinpath("boot")!s}', root_device], check=False)
68 run(['chpasswd', '--root', root], input=b'root:toor')
69
70 finally:
71 run(['umount', root])