├── .github
├── ISSUE_TEMPLATE
│ ├── audio_issue.md
│ ├── bug_report.md
│ └── feature_request.md
├── scripts
│ ├── build-image.py
│ └── combine_sizes.py
└── workflows
│ ├── close-audio-issues.yml
│ ├── close-stale-issues.yml
│ ├── test-builds.yml
│ └── update-functions.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.py
├── cli_input.py
├── configs
├── crostini
│ ├── devices.allow
│ └── setup-crostini.sh
├── debian-sources.list
├── eupnea.json
├── selinux
│ ├── fixfiles
│ ├── mountinfo
│ ├── mounts
│ └── unlabeled
└── zram
│ └── zram-generator.conf
├── distro
├── __init__.py
├── arch.py
├── debian.py
├── fedora.py
├── pop_os.py
└── ubuntu.py
├── functions.py
├── main.py
└── os_sizes.json
/.github/ISSUE_TEMPLATE/audio_issue.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Audio issue
3 | about: Please create audio issues in the audio-scripts repo!
4 | title: "[AUDIO] "
5 | labels: 'wontfix'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **PLEASE CREATE AUDIO ISSUES IN THE [audio-scripts](https://github.com/eupnea-linux/audio-scripts) REPOSITORY!**
11 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a bug report
4 | title: "[BUG] "
5 | labels: 'bug'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Run ``git clone --depth=1 https://github.com/eupnea-project/depthboot-builder; cd depthboot-builder; ./main.py``
16 | 2. Select ... as distro
17 | 3. Select ... as desktop environment
18 | 4. ...
19 |
20 | **Full log**
21 |
22 | Verbose log:
23 |
24 |
25 | **Build system (please complete the following information):**
26 | - OS: [e.g. Ubuntu, Windows Subsystem for Linux, Crostini(aka Linux on ChromeOS)]
27 |
28 | **Additional context**
29 | Add any other context about the problem here.
30 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: "[FEATURE REQUEST] "
5 | labels: 'enhancement'
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Additional context**
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/.github/scripts/build-image.py:
--------------------------------------------------------------------------------
1 | # This script is purely for automatic purposes, it is not meant to be used by end users.
2 |
3 | import argparse
4 | import sys
5 | from pathlib import Path
6 |
7 | import build
8 |
9 |
10 | def print_header(message: str) -> None:
11 | print("\033[95m" + message + "\033[0m", flush=True)
12 |
13 |
14 | def print_error(message: str) -> None:
15 | print("\033[91m" + message + "\033[0m", flush=True)
16 |
17 |
18 | def process_args():
19 | parser = argparse.ArgumentParser()
20 | parser.add_argument(dest="distro_name", type=str, help="Distro name")
21 | parser.add_argument(dest="distro_version", type=str, help="Distro version")
22 | parser.add_argument(dest="de_name", type=str, help="DE name")
23 | return parser.parse_args()
24 |
25 |
26 | if __name__ == "__main__":
27 | args = process_args()
28 | build_args = argparse.Namespace()
29 | build_args.verbose = True
30 | build_args.verbose_kernel = True
31 | build_args.local_path = None
32 | build_args.dev_build = False
33 | build_args.no_shrink = False
34 | build_args.image_size = [10]
35 | testing_dict = {
36 | "distro_name": args.distro_name,
37 | "distro_version": args.distro_version,
38 | "de_name": args.de_name,
39 | "username": "localuser",
40 | "password": "test",
41 | "device": "image",
42 | "kernel_type": "mainline"
43 | }
44 |
45 | # Start testing
46 | print_header(f"Testing {args.distro_name} + {args.distro_version} + {args.de_name}")
47 | try:
48 | build.start_build(build_options=testing_dict, args=build_args)
49 | # calculate shrunk image size in gb and round it to 2 decimal places
50 | image_size = round(Path("./depthboot.img").stat().st_size / 1073741824, 1)
51 | except Exception as e:
52 | print_error(str(e))
53 | print_error(f"Failed to build {args.distro_name} + {args.distro_version} + {args.de_name}")
54 | image_size = 0
55 |
56 | with open(f"{args.distro_name}_{args.distro_version}_{args.de_name}_results.txt", "w") as f:
57 | f.write(str(image_size))
58 |
--------------------------------------------------------------------------------
/.github/scripts/combine_sizes.py:
--------------------------------------------------------------------------------
1 | import contextlib
2 | import json
3 | import glob
4 |
5 | if __name__ == "__main__":
6 | # open the sizes files in each result's directory
7 | files = glob.glob("./results_*/*_results.txt")
8 | all_sizes = {}
9 | for file in files:
10 | with open(file, "r") as f:
11 | data = f.read()
12 | distro_name = file.split("/")[2].split("_")[0]
13 | distro_version = file.split("/")[2].split("_")[1]
14 | de_name = file.split("/")[2].split("_")[2]
15 | try:
16 | all_sizes[f"{distro_name}_{distro_version}"][de_name] = float(data)
17 | except KeyError:
18 | all_sizes[f"{distro_name}_{distro_version}"] = {de_name: float(data)}
19 |
20 | # Sometimes the builder script fails due to a network error -> the size is 0 -> replace with old size
21 | # open old sizes file
22 | # with open("os_sizes.json", "r") as f:
23 | # old_sizes = json.load(f)
24 | # for distro in all_sizes:
25 | # for key in all_sizes[distro]:
26 | # if all_sizes[distro][key] == 0:
27 | # all_sizes[distro][key] = old_sizes[distro][key]
28 |
29 | # # Calculate average sizes
30 | # for distro in all_sizes:
31 | # total_GB = 0
32 | # total_amount = 0
33 | # for key in all_sizes[distro]:
34 | # total_GB += all_sizes[distro][key]
35 | # total_amount += 1
36 | # # calculate average size and cast to 1 decimal place
37 | # all_sizes[distro]["average"] = round(total_GB / total_amount, 1)
38 |
39 | # Calculate raw DE sizes
40 | for distro in all_sizes:
41 | for key in all_sizes[distro]:
42 | if key != "cli":
43 | with contextlib.suppress(KeyError): # the distro_average dicts obv don't have a cli key
44 | all_sizes[distro][key] = round(all_sizes[distro][key] - all_sizes[distro]["cli"] / 2, 1)
45 |
46 | # Calculate average sizes for distros with multiple versions
47 | all_sizes["ubuntu_average"] = round(
48 | (all_sizes["ubuntu_22.04"]["cli"] + all_sizes["ubuntu_23.10"]["cli"]) / 2, 1)
49 | all_sizes["fedora_average"] = round((all_sizes["fedora_39"]["cli"] + all_sizes["fedora_40"]["cli"]) / 2, 1)
50 |
51 | with open("os_sizes.json", "w") as f:
52 | json.dump(all_sizes, f, indent=2, sort_keys=True)
53 |
--------------------------------------------------------------------------------
/.github/workflows/close-audio-issues.yml:
--------------------------------------------------------------------------------
1 | name: Close audio issue
2 | on:
3 | issues:
4 | types: [opened]
5 |
6 | jobs:
7 | close-audio-issues:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - if: startsWith(github.event.issue.title, '[AUDIO]')
11 | name: Close Issue
12 | uses: peter-evans/close-issue@v2
13 | with:
14 | close-reason: not_planned
15 | comment: |
16 | Please post audio issues in [audio-scripts](https://github.com/eupnea-project/audio-scripts) repository.
17 | Auto-closing this issue.
--------------------------------------------------------------------------------
/.github/workflows/close-stale-issues.yml:
--------------------------------------------------------------------------------
1 | name: Close inactive issues
2 | on:
3 | schedule:
4 | - cron: "0 0 * * *" # run at the start of every day
5 |
6 | jobs:
7 | close-issues:
8 | runs-on: ubuntu-latest
9 | permissions:
10 | issues: write
11 | pull-requests: write
12 | steps:
13 | - uses: actions/stale@v4
14 | with:
15 | days-before-issue-stale: 14
16 | days-before-issue-close: 7
17 | stale-issue-label: "stale"
18 | stale-issue-message: "This issue has been marked as stale because it has been open for 14 days with no activity."
19 | close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale."
20 | days-before-pr-stale: -1
21 | days-before-pr-close: -1
22 | repo-token: ${{ secrets.GITHUB_TOKEN }}
23 |
--------------------------------------------------------------------------------
/.github/workflows/test-builds.yml:
--------------------------------------------------------------------------------
1 | name: Testing builds
2 | on:
3 | schedule:
4 | - cron: "0 3 * * *" # run at the start of every day after functions.py is updated
5 | workflow_dispatch:
6 |
7 | concurrency:
8 | group: ${{ github.ref }}
9 | cancel-in-progress: true
10 |
11 | jobs:
12 | test-ubuntu:
13 | strategy:
14 | matrix:
15 | version: [ "22.04", "23.10" ]
16 | de_name: [ "gnome", "kde", "xfce", "lxqt", "budgie", "deepin", "cinnamon", "cli" ]
17 | runs-on: ubuntu-latest
18 | steps:
19 | - name: Maximizing build space
20 | uses: easimon/maximize-build-space@master
21 | with:
22 | temp-reserve-mb: 11264
23 | swap-size-mb: 1
24 | remove-dotnet: 'true'
25 | remove-android: 'true'
26 | remove-haskell: 'true'
27 |
28 | - name: Checking out repository code
29 | uses: actions/checkout@v3
30 | with:
31 | fetch-depth: 1
32 |
33 | - name: Installing dependencies
34 | run: sudo apt-get update && sudo apt-get install -y cgpt vboot-kernel-utils parted
35 |
36 | - name: Copy testing script to root
37 | run: cp ./.github/scripts/build-image.py ./build-image.py
38 |
39 | - name: Testing Ubuntu builds
40 | run: sudo python3 ./build-image.py ubuntu ${{ matrix.version }} ${{ matrix.de_name }}
41 |
42 | - name: Uploading result as artifact
43 | uses: actions/upload-artifact@v3
44 | with:
45 | name: results_ubuntu_${{ matrix.version }}_${{ matrix.de_name }}
46 | retention-days: 1
47 | path: |
48 | *_results.txt
49 |
50 | test-arch:
51 | strategy:
52 | matrix:
53 | de_name: [ "gnome", "kde", "xfce", "lxqt", "budgie", "deepin", "cinnamon", "cli" ]
54 | runs-on: ubuntu-latest
55 | steps:
56 | - name: Maximizing build space
57 | uses: easimon/maximize-build-space@master
58 | with:
59 | temp-reserve-mb: 11264
60 | swap-size-mb: 1
61 | remove-dotnet: 'true'
62 | remove-android: 'true'
63 | remove-haskell: 'true'
64 |
65 | - name: Checking out repository code
66 | uses: actions/checkout@v3
67 | with:
68 | fetch-depth: 1
69 |
70 | - name: Installing dependencies
71 | run: sudo apt-get update && sudo apt-get install -y cgpt vboot-kernel-utils parted
72 |
73 | - name: Copy testing script to root
74 | run: cp ./.github/scripts/build-image.py ./build-image.py
75 |
76 | - name: Testing Arch builds
77 | run: sudo python3 ./build-image.py arch latest ${{ matrix.de_name }}
78 |
79 | - name: Uploading result as artifact
80 | uses: actions/upload-artifact@v3
81 | with:
82 | name: results_arch_latest_${{ matrix.de_name }}
83 | retention-days: 1
84 | path: |
85 | *_results.txt
86 |
87 | test-fedora:
88 | strategy:
89 | matrix:
90 | version: [ "39", "40" ]
91 | de_name: [ "gnome", "kde", "xfce", "lxqt", "deepin", "budgie", "cinnamon", "cli" ]
92 | runs-on: ubuntu-latest
93 | steps:
94 | - name: Maximizing build space
95 | uses: easimon/maximize-build-space@master
96 | with:
97 | temp-reserve-mb: 11264
98 | swap-size-mb: 1
99 | remove-dotnet: 'true'
100 | remove-android: 'true'
101 | remove-haskell: 'true'
102 |
103 | - name: Checking out repository code
104 | uses: actions/checkout@v3
105 | with:
106 | fetch-depth: 1
107 |
108 | - name: Installing dependencies
109 | run: sudo apt-get update && sudo apt-get install -y cgpt vboot-kernel-utils parted
110 |
111 | - name: Copy testing script to root
112 | run: cp ./.github/scripts/build-image.py ./build-image.py
113 |
114 | - name: Testing Fedora builds
115 | run: sudo python3 ./build-image.py fedora ${{ matrix.version }} ${{ matrix.de_name }}
116 |
117 | - name: Uploading result as artifact
118 | uses: actions/upload-artifact@v3
119 | with:
120 | name: results_fedora_${{ matrix.version }}_${{ matrix.de_name }}
121 | retention-days: 1
122 | path: |
123 | *_results.txt
124 |
125 | test-debian:
126 | strategy:
127 | matrix:
128 | de_name: [ "gnome", "kde", "xfce", "lxqt", "budgie", "cinnamon", "cli" ]
129 | runs-on: ubuntu-latest
130 | steps:
131 | - name: Maximizing build space
132 | uses: easimon/maximize-build-space@master
133 | with:
134 | temp-reserve-mb: 11264
135 | swap-size-mb: 1
136 | remove-dotnet: 'true'
137 | remove-android: 'true'
138 | remove-haskell: 'true'
139 |
140 | - name: Checking out repository code
141 | uses: actions/checkout@v3
142 | with:
143 | fetch-depth: 1
144 |
145 | - name: Installing dependencies
146 | run: sudo apt-get update && sudo apt-get install -y cgpt vboot-kernel-utils parted
147 |
148 | - name: Copy testing script to root
149 | run: cp ./.github/scripts/build-image.py ./build-image.py
150 |
151 | - name: Testing Debian builds
152 | run: sudo python3 ./build-image.py debian stable ${{ matrix.de_name }}
153 |
154 | - name: Uploading result as artifact
155 | uses: actions/upload-artifact@v3
156 | with:
157 | name: results_debian_stable_${{ matrix.de_name }}
158 | retention-days: 1
159 | path: |
160 | *_results.txt
161 |
162 | test-pop-os:
163 | runs-on: ubuntu-latest
164 | steps:
165 | - name: Checking out repository code
166 | uses: actions/checkout@v3
167 | with:
168 | fetch-depth: 1
169 |
170 | - name: Installing dependencies
171 | run: sudo apt-get update && sudo apt-get install -y cgpt vboot-kernel-utils parted
172 |
173 | - name: Copy testing script to root
174 | run: cp ./.github/scripts/build-image.py ./build-image.py
175 |
176 | - name: Testing PopOS build
177 | run: sudo python3 ./build-image.py pop-os 22.04 cosmic-gnome
178 |
179 | - name: Uploading result as artifact
180 | uses: actions/upload-artifact@v3
181 | with:
182 | name: results_pop-os_22.04_cosmic-gnome
183 | retention-days: 1
184 | path: |
185 | *_results.txt
186 |
187 | evaluate-results:
188 | needs: [ test-ubuntu, test-arch, test-fedora, test-pop-os, test-debian ]
189 | runs-on: ubuntu-latest
190 | steps:
191 | - name: Checking out repository code
192 | uses: actions/checkout@v3
193 | with:
194 | fetch-depth: 1
195 |
196 | - name: Downloading result artifacts
197 | uses: actions/download-artifact@v3
198 |
199 | - name: Combining sizes into one json file
200 | run: python3 ./.github/scripts/combine_sizes.py
201 |
202 | - uses: stefanzweifel/git-auto-commit-action@v4
203 | with:
204 | # Disable setting repo owner as commit author
205 | commit_user_name: github-actions[bot]
206 | commit_user_email: 41898282+github-actions[bot]@users.noreply.github.com
207 | commit_author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
208 |
209 | # Optional. Commit message for the created commit.
210 | # Defaults to "Apply automatic changes"
211 | commit_message: "chore: update os_sizes.json"
212 |
213 | # Optional glob pattern of files which should be added to the commit
214 | # Defaults to all (.)
215 | # See the `pathspec`-documentation for git
216 | # - https://git-scm.com/docs/git-add#Documentation/git-add.txt-ltpathspecgt82308203
217 | # - https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec
218 | file_pattern: 'os_sizes.json'
219 |
220 | - name: Evaluating results
221 | # Check if the results are not empty and fail the whole workflow if they are
222 | run: |
223 | for file in ./results_*/*_results.txt
224 | do
225 | if [ "$(cat $file)" == "0" ]
226 | then
227 | echo $file >> ./failed_results.txt
228 | fi
229 | done
230 | if [ -s ./failed_results.txt ]
231 | then
232 | echo "Failed to build the following images:"
233 | cat ./failed_results.txt
234 | exit 1
235 | fi
236 |
--------------------------------------------------------------------------------
/.github/workflows/update-functions.yml:
--------------------------------------------------------------------------------
1 | name: Updating functions.py
2 | on:
3 | schedule:
4 | - cron: "0 0 * * *" # run at the start of every day
5 | workflow_dispatch:
6 |
7 | jobs:
8 | update-functions:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: Checking out repository code
12 | uses: actions/checkout@v3
13 |
14 | - name: Cloning functions repo
15 | run: git clone https://github.com/eupnea-project/python-os-functions
16 |
17 | - name: Updating functions.py
18 | run: cp ./python-os-functions/functions.py ./functions.py
19 |
20 | - uses: stefanzweifel/git-auto-commit-action@v4
21 | with:
22 | # Disable setting repo owner as commit author
23 | commit_user_name: github-actions[bot]
24 | commit_user_email: 41898282+github-actions[bot]@users.noreply.github.com
25 | commit_author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
26 |
27 | # Optional. Commit message for the created commit.
28 | # Defaults to "Apply automatic changes"
29 | commit_message: "chore: update functions.py"
30 |
31 | # Optional glob pattern of files which should be added to the commit
32 | # Defaults to all (.)
33 | # See the `pathspec`-documentation for git
34 | # - https://git-scm.com/docs/git-add#Documentation/git-add.txt-ltpathspecgt82308203
35 | # - https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspecapathspec
36 | file_pattern: 'functions.py'
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /.idea/
2 | depthboot.img
3 | depthboot.bin
4 | kernel.flags
5 | /__pycache__/
6 | /venv/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DEPTHBOOT HAS BEEN DISCONTINUED
2 |
3 | Please use one of the following projects instead:
4 | * MrChromebox's UEFI/RW_L (turn chromebook into almost a normal laptop): https://mrchromebox.tech/#fwscript
5 | * FyraLab's submarine (does not require firmware modification): https://github.com/FyraLabs/submarine
6 |
7 |
8 | View the old readme
9 |
10 | # Depthboot: your **Chromebook**, your way
11 |
12 | Choose between a variety of common Linux distributions and desktop environments to create a bootable image for any
13 | [supported](https://eupnea-project.github.io/docs/project/supported-devices) 64-bit Chromebook, without modifying
14 | firmware.
15 |
16 |
17 | [Due to licensing restraints Depthboot cannot be distributed as an iso](https://eupnea-project.github.io/faq#why-is-sharing-depthboot-images-illegal).
18 | Instead, it has to be built locally.
19 |
20 | ## Depthboot vs Mainline
21 |
22 | (Mainline = stock, unmodified Linux distribution)
23 |
24 | **Mainline Linux:**
25 |
26 | * Requires either replacing firmware completely (UEFI) or changing a part of it (rw_legacy). Not all devices have both
27 | options and there is a slight risk of bricking the Chromebook.
28 | * Some hardware may not work (touchscreen, touchpad, etc.)
29 | * Audio is mostly unsupported.
30 |
31 | **Depthboot:**
32 |
33 | * Requires no modifications to firmware.
34 | * Hardware support matches ChromeOS.
35 | * Extensive audio support, with active development to bring further support.
36 |
37 | [Read more](https://eupnea-project.github.io/docs/chromebook/firmware-comparison)
38 |
39 | ## [Supported devices](https://eupnea-project.github.io/docs/depthboot/supported-devices)
40 |
41 | ## Credit
42 |
43 | * Depthboot is based on [Breath](https://github.com/cb-linux/breath) by MilkyDeveloper. Breath was active from Apr 2021
44 | until it's archival in late Aug 2022.
45 | * All Eupnea Project icons were made by [Inderix](https://github.com/Inderix).
46 |
47 | ## Join our Discord server:
48 |
49 | [
](https://discord.gg/XwRHSUbSmu)
50 |
--------------------------------------------------------------------------------
/build.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import argparse
3 | import atexit
4 | import json
5 | import os
6 | from urllib.error import URLError
7 |
8 | from functions import *
9 |
10 | img_mnt = "" # empty to avoid variable not defined error in exit_handler
11 |
12 |
13 | # the exit handler with user messages is in main.py
14 | def exit_handler():
15 | # Only trigger cleanup if the user initiated the exit, not if the script exited on its own
16 | exc_type = sys.exc_info()[0]
17 | if exc_type != KeyboardInterrupt:
18 | return
19 | print_error("Ctrl+C detected. Cleaning machine and exiting...")
20 | # Kill arch gpg agent if present
21 | print_status("Killing gpg-agent arch processes if they exist")
22 | gpg_pids = []
23 | for line in bash("ps aux").split("\n"):
24 | if "gpg-agent --homedir /etc/pacman.d/gnupg --use-standard-socket --daemon" in line:
25 | temp_string = line[line.find(" "):].strip()
26 | gpg_pids.append(temp_string[:temp_string.find(" ")])
27 | for pid in gpg_pids:
28 | print(f"Killing gpg-agent proces with pid: {pid}")
29 | bash(f"kill {pid}")
30 |
31 | print_status("Unmounting partitions")
32 | with contextlib.suppress(subprocess.CalledProcessError):
33 | bash("umount -lf /mnt/depthboot") # umount mountpoint
34 | sleep(5) # wait for umount to finish
35 |
36 | # unmount image/device completely from system
37 | # on crostini umount fails for some reason
38 | with contextlib.suppress(subprocess.CalledProcessError):
39 | bash(f"umount -lf {img_mnt}p*") # umount all partitions from image
40 | with contextlib.suppress(subprocess.CalledProcessError):
41 | bash(f"umount -lf {img_mnt}*") # umount all partitions from usb/sd-card
42 |
43 |
44 | # download the distro rootfs
45 | def download_rootfs(distro_name: str, distro_version: str) -> None:
46 | try:
47 | match distro_name:
48 | case "arch":
49 | print_status("Downloading latest Arch Linux rootfs from geo.mirror.pkgbuild.com")
50 | download_file("https://geo.mirror.pkgbuild.com/iso/latest/archlinux-bootstrap-x86_64.tar.gz",
51 | "/tmp/depthboot-build/arch-rootfs.tar.gz")
52 | case "ubuntu" | "fedora" | "debian":
53 | print_status(f"Downloading {distro_name.capitalize()} rootfs, version {distro_version} from "
54 | f"distro-rootfs releases")
55 | download_file(f"https://github.com/eupnea-project/distro-rootfs/releases/latest/download/"
56 | f"{distro_name}-rootfs-{distro_version}.tar.xz",
57 | f"/tmp/depthboot-build/{distro_name}-rootfs.tar.xz")
58 | case "pop-os":
59 | print_status("Downloading Pop!_OS rootfs from Eupnea GitHub")
60 | download_file("https://github.com/eupnea-project/distro-rootfs/releases/latest/download/pop-os-rootfs-"
61 | "22.04.split.aa", "/tmp/depthboot-build/pop-os-rootfs.split.aa")
62 | # print_status("Downloading pop-os rootfs from eupnea GitHub releases, part 2/2")
63 | # download_file("https://github.com/eupnea-project/pop-os-rootfs/releases/latest/download/pop-os-rootfs"
64 | # "-22.04.split.ab", "/tmp/depthboot-build/pop-os-rootfs.split.ab")
65 | print_status("Combining split Pop!_OS rootfs, might take a while")
66 | bash("cat /tmp/depthboot-build/pop-os-rootfs.split.?? > /tmp/depthboot-build/pop-os-rootfs.tar.xz")
67 | except URLError:
68 | print_error("Couldn't download rootfs. Check your internet connection and try again. If the error persists, "
69 | "create an issue with the distro and version in the name")
70 | sys.exit(1)
71 |
72 |
73 | # Create, mount, partition the img and flash the eupnea kernel
74 | def prepare_img(img_size: int) -> bool:
75 | print_status("Preparing image")
76 | try:
77 | bash(f"fallocate -l {img_size}G depthboot.img")
78 | except subprocess.CalledProcessError: # try fallocate, if it fails use dd
79 | bash(f"dd if=/dev/zero of=depthboot.img status=progress bs=1024 count={img_size * 1000000}")
80 |
81 | print_status("Mounting empty image")
82 | global img_mnt
83 | try:
84 | img_mnt = bash("losetup -f --show depthboot.img")
85 | except subprocess.CalledProcessError as e:
86 | if not bash("systemd-detect-virt").lower().__contains__("wsl"): # if not running WSL, the error is unexpected
87 | raise e
88 | print_error("Losetup failed. Make sure you are using WSL version 2 aka WSL2.")
89 | sys.exit(1)
90 | if img_mnt == "":
91 | print_error("Failed to mount image")
92 | sys.exit(1)
93 | partition(False)
94 | return False
95 |
96 |
97 | # Prepare USB/SD-card
98 | def prepare_usb_sd(device: str) -> bool:
99 | print_status("Preparing USB/SD-card")
100 |
101 | # fix device name if needed
102 | if device.endswith("/") or device.endswith("1") or device.endswith("2"):
103 | device = device[:-1]
104 | # add /dev/ to device name, if needed
105 | if not device.startswith("/dev/"):
106 | device = f"/dev/{device}"
107 |
108 | global img_mnt
109 | img_mnt = device
110 |
111 | # unmount all partitions
112 | with contextlib.suppress(subprocess.CalledProcessError):
113 | bash(f"umount -lf {img_mnt}*")
114 |
115 | if img_mnt.__contains__("mmcblk"): # sd card
116 | partition(write_usb=False)
117 | return False
118 | else:
119 | partition(write_usb=True)
120 | return True
121 |
122 |
123 | def partition(write_usb: bool) -> None:
124 | print_status("Preparing device/image partition")
125 |
126 | # Determine rootfs part name
127 | rootfs_mnt = f"{img_mnt}3" if write_usb else f"{img_mnt}p3"
128 | # remove pre-existing partition table from storage device
129 | bash(f"wipefs -af {img_mnt}")
130 |
131 | # format as per depthcharge requirements,
132 | # READ: https://wiki.gentoo.org/wiki/Creating_bootable_media_for_depthcharge_based_devices
133 | try:
134 | bash(f"parted -s {img_mnt} mklabel gpt")
135 | # TODO: Only show this prompt when parted throws: "we have been unable to inform the kernel of the change"
136 | # TODO: Check if partprob-ing the drive could fix this error
137 | except subprocess.CalledProcessError:
138 | print_error("Failed to create partition table. Try physically unplugging and replugging the USB/SD-card.")
139 | print_question("If you chose the image option or are seeing this message the second time, create an issue on "
140 | "GitHub/Discord/Revolt")
141 | sys.exit(1)
142 | bash(f"parted -s -a optimal {img_mnt} unit mib mkpart Kernel 1 65") # kernel partition
143 | # this partition is not necessary, but all the depthboot scripts were written with it in mind
144 | # -> it's easier to keep it for now
145 | # it also reserves 500mb for the kexec bootloader in the future
146 | bash(f"parted -s -a optimal {img_mnt} unit mib mkpart Kernel 65 500")
147 | bash(f"parted -s -a optimal {img_mnt} unit mib mkpart Root 500 100%") # rootfs partition
148 | bash(f"cgpt add -i 1 -t kernel -S 1 -T 5 -P 15 {img_mnt}") # set kernel flags
149 | bash(f"cgpt add -i 2 -t kernel -S 1 -T 5 -P 1 {img_mnt}") # set backup kernel flags
150 |
151 | print_status("Formatting rootfs partition")
152 | # Create rootfs ext4 partition
153 | bash(f"yes 2>/dev/null | mkfs.ext4 {rootfs_mnt}") # 2>/dev/null is to supress yes broken pipe warning
154 |
155 | # Mount rootfs partition
156 | bash(f"mount {rootfs_mnt} /mnt/depthboot")
157 |
158 | print_status("Device/image preparation complete")
159 |
160 |
161 | # extract the rootfs to /mnt/depthboot
162 | def extract_rootfs(distro_name: str, distro_version: str) -> None:
163 | print_status("Extracting rootfs")
164 | match distro_name:
165 | case "arch":
166 | print_status("Extracting Arch Linux rootfs")
167 | mkdir("/tmp/depthboot-build/arch-rootfs")
168 | extract_file("/tmp/depthboot-build/arch-rootfs.tar.gz", "/tmp/depthboot-build/arch-rootfs")
169 | cpdir("/tmp/depthboot-build/arch-rootfs/root.x86_64/", "/mnt/depthboot/")
170 | case "pop-os" | "ubuntu" | "fedora" | "debian":
171 | print_status(f"Extracting {distro_name.capitalize()} rootfs")
172 | extract_file(f"/tmp/depthboot-build/{distro_name}-rootfs.tar.xz", "/mnt/depthboot")
173 | case "generic":
174 | def prompt_user_for_rootfs():
175 | while True:
176 | # use read for path autocompletion
177 | user_rootfs_path = input("\033[92m" + "Please manually extract the rootfs and provide the path "
178 | "to the root directory:\n" + "\033[0m")
179 | if user_rootfs_path.endswith("/"):
180 | user_rootfs_path = user_rootfs_path[:-1]
181 | # we could check for more dirs but this should be enough
182 | if not path_exists(f"{user_rootfs_path}/usr") or not path_exists(f"{user_rootfs_path}/bin"):
183 | print_error("Path does not contain a rootfs. Verify that you are entering the full path, "
184 | "without any shortcuts (i.e. ~ for home, ./ for current dir, etc...)")
185 | continue
186 | return user_rootfs_path
187 |
188 | print_status("Starting generic rootfs extraction")
189 | # ask user for path to iso
190 | while True:
191 | print_warning(
192 | "You will need a full iso of the distro. Netboot, pure initrd, etc... images will not work.")
193 | # user read for path autocompletion
194 | iso_path = input("\033[92m" + "Enter full path to the ISO file:\n" + "\033[0m")
195 | if not path_exists(iso_path) or not iso_path.endswith(".iso"):
196 | print_error("File does not exist or is not an iso file. Verify that you are entering the full path,"
197 | " without any shortcuts (i.e. ~ for home, etc)")
198 | continue
199 | break
200 | # Check if running under crostini
201 | try:
202 | with open("/sys/devices/virtual/dmi/id/product_name", "r") as file:
203 | product_name = file.read().strip()
204 | except FileNotFoundError:
205 | product_name = "" # wsl doesn't have dmi info
206 | if product_name == "crosvm":
207 | print_error("Crostini doesn't support mounting iso files.")
208 | prompt_user_for_rootfs()
209 | # mount iso
210 | print_status("Mounting iso")
211 | iso_loop_dev = bash(f"losetup -fP --show {iso_path}")
212 | mkdir("/tmp/depthboot-build/iso-mount")
213 | # find the biggest partition
214 | partitions_json = json.loads(bash(f"lsblk -nbJ {iso_loop_dev} -o SIZE"))["blockdevices"]
215 | # remove first device as it's the total size
216 | partitions_json.pop(0)
217 | # find the index of the biggest partition
218 | max_index = partitions_json.index(max(partitions_json, key=lambda x: x['size'])) + 1
219 | print_status(f"Mounting biggest partition at {iso_loop_dev}p{max_index}")
220 | bash(f"mount {iso_loop_dev}p{max_index} /tmp/depthboot-build/iso-mount -o ro")
221 | # search for rootfs
222 | print_status("Searching for squashfs")
223 | file_path = ""
224 | for dirpath, dirnames, filenames in os.walk("/tmp/depthboot-build/iso-mount"):
225 | if "squashfs.img" in filenames:
226 | file_path = os.path.join(dirpath, "squashfs.img")
227 | print(f"Found squashfs.img at {file_path}")
228 | break
229 | elif "filesystem.squashfs" in filenames:
230 | file_path = os.path.join(dirpath, "filesystem.squashfs")
231 | print(f"Found filesystem.squashfs at {file_path}")
232 | break
233 | elif "rootfs.sfs" in filenames:
234 | file_path = os.path.join(dirpath, "rootfs.sfs")
235 | print(f"Found rootfs.sfs at {file_path}")
236 | break
237 | elif "image.squashfs" in filenames:
238 | file_path = os.path.join(dirpath, "image.squashfs")
239 | print(f"Found image.squashfs at {file_path}")
240 | break
241 | if not file_path:
242 | print_error("Could not find squashfs in iso")
243 | cpdir(prompt_user_for_rootfs(), "/mnt/depthboot")
244 | else:
245 | # extract rootfs
246 | print_status("Extracting squashfs")
247 | mkdir("/tmp/depthboot-build/squashfs-extract")
248 | # use os.system to show progress immediately
249 | os.system(f"unsquashfs -d /tmp/depthboot-build/squashfs-extract {file_path}")
250 |
251 | # check if a real rootfs was extracted or an img file
252 | if path_exists("/tmp/depthboot-build/squashfs-extract/usr") and path_exists(
253 | "/tmp/depthboot-build/squashfs-extract/bin"):
254 | print_status("Found rootfs in squashfs, copying to image/device")
255 | cpdir("/tmp/depthboot-build/squashfs-extract/", "/mnt/depthboot")
256 | else:
257 | # find img file
258 | print_status("Searching for img file in extracted squashfs")
259 | img_file_path = ""
260 | for dirpath, dirnames, filenames in os.walk("/tmp/depthboot-build/squashfs-extract"):
261 | for file in filenames:
262 | if file.endswith(".img"):
263 | img_file_path = os.path.join(dirpath, file)
264 | print(f"Found rootfs img at {img_file_path}")
265 | break
266 | if not img_file_path:
267 | print_error("Could not find rootfs img in squashfs")
268 | cpdir(prompt_user_for_rootfs(), "/mnt/depthboot")
269 | else:
270 | # mount img file
271 | print_status("Mounting img file")
272 | img_loop_dev = bash(f"losetup -fP --show {img_file_path}")
273 | mkdir("/tmp/depthboot-build/img-mount")
274 | bash(f"mount {img_loop_dev} /tmp/depthboot-build/img-mount -o ro")
275 | # search for rootfs
276 | print_status("Searching for rootfs inside img")
277 | img_rootfs_path = ""
278 | for dirpath, dirnames, filenames in os.walk("/tmp/depthboot-build/img-mount"):
279 | if "usr" in dirnames and "bin" in dirnames:
280 | img_rootfs_path = dirpath
281 | print(f"Found rootfs at {img_rootfs_path}")
282 | break
283 | if not img_rootfs_path:
284 | print_error("Could not find rootfs inside img")
285 | cpdir(prompt_user_for_rootfs(), "/mnt/depthboot")
286 | else:
287 | cpdir(img_rootfs_path, "/mnt/depthboot")
288 |
289 | print_status("\n" + "Rootfs extraction complete")
290 |
291 |
292 | # Configure distro agnostic options
293 | def post_extract(build_options) -> None:
294 | print_status("Applying distro agnostic configuration")
295 | if build_options["distro_name"] != "generic":
296 | # Create a temporary resolv.conf for internet inside the chroot
297 | mkdir("/mnt/depthboot/run/systemd/resolve", create_parents=True) # dir doesnt exist coz systemd didnt run
298 | open("/mnt/depthboot/run/systemd/resolve/stub-resolv.conf", "w").close() # create empty file for mount
299 | # Bind mount host resolv.conf to chroot resolv.conf.
300 | # If chroot /etc/resolv.conf is a symlink, then it will be resolved to the real file and bind mounted
301 | # This is needed for internet inside the chroot
302 | bash("mount --bind /etc/resolv.conf /mnt/depthboot/etc/resolv.conf")
303 |
304 | # the following mounts are mostly unneeded, but will produce a lot of warnings if not mounted
305 | # even though the resulting image will work as intended and won't have any issues
306 | # mounting the full directories results in broken host systems -> only mount what's explicitly needed
307 |
308 | # systemd needs /proc to not throw warnings
309 | bash("mount --types proc /proc /mnt/depthboot/proc")
310 |
311 | # pacman needs the /dev/fd to not throw warnings
312 | # check if link already exists, if not, create it
313 | if not path_exists("/mnt/depthboot/dev/fd"):
314 | bash("cd /mnt/depthboot && ln -s /proc/self/fd ./dev/fd")
315 |
316 | # create new /dev/pts for apt to be able to write logs and not throw warnings
317 | mkdir("/mnt/depthboot/dev/pts", create_parents=True)
318 | bash("mount --types devpts devpts /mnt/depthboot/dev/pts")
319 |
320 | # create depthboot settings file for postinstall scripts to read
321 | with open("configs/eupnea.json", "r") as settings_file:
322 | settings = json.load(settings_file)
323 | settings["distro_name"] = build_options["distro_name"]
324 | settings["distro_version"] = build_options["distro_version"]
325 | settings["de_name"] = build_options["de_name"]
326 | if build_options["device"] != "image":
327 | settings["install_type"] = "direct"
328 | with open("/mnt/depthboot/etc/eupnea.json", "w") as settings_file:
329 | json.dump(settings, settings_file)
330 |
331 | print_status("Cleaning /boot")
332 | rmdir("/mnt/depthboot/boot") # clean stock kernels from /boot
333 |
334 | if build_options["distro_name"] == "fedora":
335 | print_status("Enabling resolved.conf systemd service")
336 | # systemd-resolved.service needed to create /etc/resolv.conf link. Not enabled by default on fedora
337 | # on other distros networkmanager takes care of this
338 | chroot("systemctl enable systemd-resolved")
339 |
340 | print_status("Configuring user")
341 | username = build_options["username"] # quotes interfere with functions below
342 | chroot(f"useradd --create-home --shell /bin/bash {username}")
343 | password = build_options["password"] # quotes interfere with functions below
344 | chroot(f"echo '{username}:{password}' | chpasswd")
345 | with open("/mnt/depthboot/etc/group", "r") as group_file:
346 | group_lines = group_file.readlines()
347 | for line in group_lines:
348 | match line.split(":")[0]:
349 | case "sudo":
350 | chroot(f"usermod -aG sudo {username}")
351 | case "wheel":
352 | chroot(f"usermod -aG wheel {username}")
353 | case "doas":
354 | chroot(f"usermod -aG doas {username}")
355 |
356 | # set timezone build system timezone on device
357 | # In some environments(Crouton), the timezone is not set -> ignore in that case
358 | with contextlib.suppress(subprocess.CalledProcessError):
359 | host_time_zone = bash("file /etc/localtime") # read host timezone link
360 | host_time_zone = host_time_zone[host_time_zone.find("/usr/share/zoneinfo/"):].strip() # get actual timezone
361 | chroot(f"ln -sf {host_time_zone} /etc/localtime")
362 |
363 | print_status("Distro agnostic configuration complete")
364 |
365 |
366 | # post extract and distro config
367 | def post_config(distro_name: str, verbose_kernel: bool, kernel_type: str, is_usb,
368 | local_path: str) -> None:
369 | if distro_name != "generic":
370 | # Enable postinstall service
371 | print_status("Enabling postinstall service")
372 | chroot("systemctl enable eupnea-postinstall.service")
373 |
374 | # if local path option was used, extract modules and headers to the rootfs
375 | # check if at least kernel image and modules exist as otherwise the kernel won't boot
376 | if path_exists(f"{local_path}modules.tar.xz") and path_exists(f"{local_path}bzImage"):
377 | print_status("Extracting kernel modules from local path to rootfs")
378 | extract_file(f"{local_path}modules.tar.xz", "/mnt/depthboot/lib/modules/")
379 | kernel_path = f"{local_path}bzImage" # set kernel path to local path
380 | if path_exists(f"{local_path}headers.tar.xz"): # kernel headers are not required to boot
381 | print_status("Extracting kernel headers from local path")
382 | extract_file(f"{local_path}headers.tar.xz", "/mnt/depthboot/usr/src/")
383 | else:
384 | kernel_path = f"/mnt/depthboot/boot/vmlinuz-eupnea-{kernel_type}"
385 |
386 | # flash kernel
387 | # get uuid of rootfs partition
388 | rootfs_mnt = f"{img_mnt}3" if is_usb else f"{img_mnt}p3"
389 | rootfs_partuuid = bash(f"blkid -o value -s PARTUUID {rootfs_mnt}")
390 | print_status(f"Rootfs partition UUID: {rootfs_partuuid}")
391 |
392 | # write PARTUUID to kernel flags and save it as a file
393 | base_string = "console= root=PARTUUID=insert_partuuid i915.modeset=1 rootwait rw fbcon=logo-pos:center,logo-count:1"
394 | if distro_name in {"pop-os", "ubuntu"}:
395 | base_string += ' security=apparmor'
396 | if distro_name == 'fedora':
397 | base_string += ' security=selinux'
398 | if verbose_kernel:
399 | base_string = base_string.replace("console=", "loglevel=15")
400 | with open("kernel.flags", "w") as config:
401 | config.write(base_string.replace("insert_partuuid", rootfs_partuuid))
402 |
403 | print_status("Flashing kernel to device/image")
404 | # Sign kernel
405 | bash("futility vbutil_kernel --arch x86_64 --version 1 --keyblock /usr/share/vboot/devkeys/kernel.keyblock "
406 | "--signprivate /usr/share/vboot/devkeys/kernel_data_key.vbprivk --bootloader kernel.flags "
407 | f"--config kernel.flags --vmlinuz {kernel_path} --pack /tmp/depthboot-build/bzImage.signed")
408 |
409 | # if image is a loop device, add a p in the partition name
410 | bash(f"dd if=/tmp/depthboot-build/bzImage.signed of={img_mnt}{'1' if is_usb else 'p1'}")
411 |
412 | # Fedora requires all files to be relabled for SELinux to work
413 | # If this is not done, SELinux will prevent users from logging in
414 | if distro_name == "fedora":
415 | print_status("Relabeling files for SELinux")
416 |
417 | # The following script needs some specific files in /proc -> unmount /proc
418 | bash("umount -lR /mnt/depthboot/proc")
419 |
420 | # copy /proc files needed for fixfiles
421 | mkdir("/mnt/depthboot/proc/self")
422 | cpfile("configs/selinux/mounts", "/mnt/depthboot/proc/self/mounts")
423 | cpfile("configs/selinux/mountinfo", "/mnt/depthboot/proc/self/mountinfo")
424 |
425 | # copy /sys files needed for fixfiles
426 | mkdir("/mnt/depthboot/sys/fs/selinux/initial_contexts/", create_parents=True)
427 | cpfile("configs/selinux/unlabeled", "/mnt/depthboot/sys/fs/selinux/initial_contexts/unlabeled")
428 |
429 | # Backup original selinux
430 | cpfile("/mnt/depthboot/usr/sbin/fixfiles", "/mnt/depthboot/usr/sbin/fixfiles.bak")
431 | # Copy patched fixfiles script
432 | cpfile("configs/selinux/fixfiles", "/mnt/depthboot/usr/sbin/fixfiles")
433 |
434 | chroot("/sbin/fixfiles -T 0 restore")
435 |
436 | # Restore original fixfiles
437 | cpfile("/mnt/depthboot/usr/sbin/fixfiles.bak", "/mnt/depthboot/usr/sbin/fixfiles")
438 | rmfile("/mnt/depthboot/usr/sbin/fixfiles.bak")
439 |
440 | # Clean all temporary files from image/sd-card to reduce its size
441 | rmdir("/mnt/depthboot/tmp")
442 | # rmdir("/mnt/depthboot/var/tmp")
443 | # rmdir("/mnt/depthboot/var/cache")
444 | # rmdir("/mnt/depthboot/proc")
445 | # rmdir("/mnt/depthboot/run")
446 | # rmdir("/mnt/depthboot/sys")
447 | # rmdir("/mnt/depthboot/lost+found")
448 | # rmdir("/mnt/depthboot/dev")
449 |
450 | # Unmount everything
451 | with contextlib.suppress(subprocess.CalledProcessError): # will throw errors for unmounted paths
452 | bash("umount -lR /mnt/depthboot") # recursive unmount
453 |
454 |
455 | # the main build function
456 | def start_build(build_options: dict, args: argparse.Namespace) -> None:
457 | if args.verbose:
458 | print(args)
459 | set_verbose(args.verbose)
460 | atexit.register(exit_handler)
461 | print_status("Starting build")
462 |
463 | print_status("Creating temporary build directory + mount point")
464 | mkdir("/tmp/depthboot-build", create_parents=True)
465 | mkdir("/mnt/depthboot", create_parents=True)
466 |
467 | local_path_posix = ""
468 | if args.local_path is None: # default
469 | download_rootfs(build_options["distro_name"], build_options["distro_version"])
470 | else: # if local path is specified, copy files from it, instead of downloading from the internet
471 | print_status("Copying local files to /tmp/depthboot-build")
472 | # clean local path string
473 | local_path_posix = args.local_path if args.local_path.endswith("/") else f"{args.local_path}/"
474 |
475 | # copy distro rootfs
476 | try:
477 | cpfile(f"{local_path_posix}rootfs.tar.xz",
478 | f"/tmp/depthboot-build/{build_options['distro_name']}-rootfs.tar.xz")
479 | except FileNotFoundError:
480 | print_warning(f"File 'rootfs.tar.xz' not found in {args.local_path}. Attempting to download rootfs")
481 | download_rootfs(build_options["distro_name"], build_options["distro_version"])
482 |
483 | # Setup device
484 | if build_options["device"] == "image":
485 | is_usb = prepare_img(args.image_size[0])
486 | else:
487 | is_usb = prepare_usb_sd(build_options["device"])
488 | # Extract rootfs and configure distro agnostic settings
489 | extract_rootfs(build_options["distro_name"], build_options["distro_version"])
490 | post_extract(build_options)
491 |
492 | match build_options["distro_name"]:
493 | case "ubuntu":
494 | import distro.ubuntu as distro
495 | case "debian":
496 | import distro.debian as distro
497 | case "arch":
498 | import distro.arch as distro
499 | case "fedora":
500 | import distro.fedora as distro
501 | case "pop-os":
502 | import distro.pop_os as distro
503 | case _:
504 | print_status("Generic install, skipping distro specific configuration")
505 | with contextlib.suppress(UnboundLocalError):
506 | distro.config(build_options["de_name"], build_options["distro_version"], args.verbose,
507 | build_options["kernel_type"])
508 |
509 | post_config(build_options["distro_name"], args.verbose_kernel, build_options["kernel_type"], is_usb,
510 | local_path_posix)
511 |
512 | print_status("Unmounting image/device")
513 |
514 | bash("sync") # write all pending changes to usb
515 |
516 | # unmount image/device completely from system
517 | # on crostini umount fails for some reason
518 | with contextlib.suppress(subprocess.CalledProcessError):
519 | bash(f"umount -lR {img_mnt}p*") # umount all partitions from image
520 | with contextlib.suppress(subprocess.CalledProcessError):
521 | bash(f"umount -lR {img_mnt}*") # umount all partitions from usb/sd-card
522 |
523 | # unmount any isos/images from /tmp/depthboot-build
524 | with contextlib.suppress(subprocess.CalledProcessError):
525 | bash("umount -lR /tmp/depthboot-build/*")
526 |
527 | # inform users about existence of system installers on the iso files
528 | if build_options["distro_name"] == "generic":
529 | print_header("Generic ISOs usually include a system installer. Do not use it, as it will try to install the "
530 | "distro in a traditional way. Instead, use 'install-to-internal' from the eupnea-utils repo if you"
531 | " wish to install your distro to the internal disk.")
532 | input("\033[92m" + "Press Enter to continue" + "\033[0m")
533 |
534 | if build_options["device"] == "image":
535 | try:
536 | with open("/sys/devices/virtual/dmi/id/product_name", "r") as file:
537 | product_name = file.read().strip()
538 | except FileNotFoundError: # WSL doesnt have dmi data
539 | product_name = ""
540 | # TODO: Fix shrinking on Crostini
541 | if product_name != "crosvm" and not args.no_shrink:
542 | # Shrink image to actual size
543 | print_status("Shrinking image")
544 | bash(f"e2fsck -fpv {img_mnt}p3") # Force check filesystem for errors
545 | bash(f"resize2fs -f -M {img_mnt}p3")
546 | block_count = int(bash(f"dumpe2fs -h {img_mnt}p3 | grep 'Block count:'")[12:].split()[0])
547 | actual_fs_in_bytes = block_count * 4096
548 | # the kernel part is always the same size -> sector amount: 131072 * 512 => 67108864 bytes
549 | # There are 2 kernel partitions -> 67108864 bytes * 2 = 134217728 bytes
550 | actual_fs_in_bytes += 134217728
551 | actual_fs_in_bytes += 20971520 # add 20mb for linux to be able to boot properly
552 | bash(f"truncate --size={actual_fs_in_bytes} ./depthboot.img")
553 | print_header(f"The ready-to-boot {build_options['distro_name'].capitalize()} Depthboot image is located at "
554 | f"{get_full_path('.')}/depthboot.img")
555 | if product_name == "crosvm":
556 | # rename the image to .bin for the chromeos recovery utility to be able to flash it
557 | bash("mv ./depthboot.img ./depthboot.bin")
558 | print_header(f"The ready-to-boot {build_options['distro_name'].capitalize()} Depthboot image is located at "
559 | f"{get_full_path('.')}/depthboot.bin")
560 | bash(f"losetup -d {img_mnt}") # unmount image from loop device
561 | else:
562 | print_header(f"USB/SD-card is ready to boot {build_options['distro_name'].capitalize()}")
563 | print_header("It is safe to remove the USB-drive/SD-card now.")
564 | print_header("Please report any bugs/issues on GitHub or on the Discord server.")
565 |
566 |
567 | if __name__ == "__main__":
568 | print_error("Do not run this file directly. Instead, run main.py")
569 |
--------------------------------------------------------------------------------
/cli_input.py:
--------------------------------------------------------------------------------
1 | import atexit
2 | import json
3 | import termios
4 | import tty
5 | from getpass import getpass
6 | from itertools import zip_longest
7 |
8 | from functions import *
9 |
10 |
11 | def get_user_input(verbose_kernel: bool, skip_device: bool = False) -> dict:
12 | output_dict = {
13 | "distro_name": "",
14 | "distro_version": "",
15 | "de_name": "",
16 | "username": "",
17 | "password": "",
18 | "device": "image",
19 | "kernel_type": ""
20 | }
21 | # Print welcome message
22 | print_header("Welcome to Depthboot, formerly known as Breath!\n"
23 | "This script will create a bootable Linux image.\n"
24 | "You can press Ctrl+C at any time to stop the script.\n"
25 | "Select the default options if you are unsure.")
26 | input("Press Enter to continue...")
27 |
28 | # open os_sizes.json
29 | with open("os_sizes.json", "r") as f:
30 | os_sizes = json.load(f)
31 |
32 | while True:
33 | distro_name = ia_selection("Which Linux distribution (flavor) would you like to use?",
34 | options=["Fedora", "Debian", "Ubuntu", "Pop!_OS", "Arch", "Generic ISO"],
35 | flags=[f"~{os_sizes['fedora_average']}GB (recommended)",
36 | f"{os_sizes['debian_stable']['cli']}GB",
37 | f"~{os_sizes['ubuntu_average']}GB",
38 | f"{os_sizes['pop-os_22.04']['cosmic-gnome']}GB",
39 | f"{os_sizes['arch_latest']['cli']}GB",
40 | "(NOT recommended)"])
41 | skip_de_selection = False
42 | match distro_name:
43 | case "Ubuntu":
44 | output_dict["distro_name"] = "ubuntu"
45 | output_dict["distro_version"] = ia_selection("Which Ubuntu version would you like to use?",
46 | options=["23.10", "22.04"], flags=[
47 | f"{os_sizes['ubuntu_23.10']['cli']}GB (latest, recommended)",
48 | f"{os_sizes['ubuntu_22.04']['cli']}GB (LTS version)"])
49 | break
50 | case "Debian":
51 | output_dict["distro_name"] = "debian"
52 | output_dict["distro_version"] = "stable"
53 | break
54 | case "Arch":
55 | output_dict["distro_name"] = "arch"
56 | output_dict["distro_version"] = "latest"
57 | break
58 | case "Fedora":
59 | output_dict["distro_name"] = "fedora"
60 | output_dict["distro_version"] = ia_selection("Which Fedora version would you like to use?",
61 | options=["39", "40"],
62 | flags=[f"~{os_sizes['fedora_39']['cli']}GB "
63 | f"(stable, recommended)",
64 | f"~{os_sizes['fedora_40']['cli']}GB"
65 | " (beta, unrecommended)"])
66 | break
67 | case "Pop!_OS":
68 | output_dict["distro_name"] = "pop-os"
69 | output_dict["distro_version"] = "22.04"
70 | break
71 | case "Generic ISO":
72 | print_error("Please strongly consider using a supported distro, as generic ISO installs are not "
73 | "optimized in any way. Generic installs will not get any kernel updates or Chromebook "
74 | "specific fixes from the Eupnea team.")
75 | print_error("Keep in mind that this will not create a live iso, but rather a real system install, "
76 | "which can be optionally installed to internal or be used from the usb/sd card directly.")
77 | while True:
78 | user_selection = ia_selection("Are you sure you want to continue?", options=["No", "Yes"], )
79 | if user_selection == "No":
80 | print_warning("Exiting...")
81 | print_header('Restart the script with: "./main.py" if you want to use a supported distro.')
82 | sys.exit(0)
83 | break
84 | print_error("Generic ISO installs are not supported by the Eupnea team. Issues/support tickets for "
85 | "generic installs will be auto-closed immediately.\n"
86 | "This script does NOT guarantee that the image will boot and you might have to manually "
87 | "debug and fix the issue **YOURSELF**")
88 | while True:
89 | user_selection = ia_selection("Are you sure you want to continue?", options=["No", "Yes"], )
90 | if user_selection == "No":
91 | print_warning("Exiting...")
92 | print_header('Restart the script with: "./main.py" if you want to use a supported distro.')
93 | sys.exit(0)
94 | break
95 | output_dict["distro_name"] = "generic"
96 | output_dict["distro_version"] = "generic"
97 | output_dict["de_name"] = "generic"
98 | break
99 |
100 | temp_distro_name = f'{output_dict["distro_name"]}_{output_dict["distro_version"]}'
101 |
102 | if output_dict["distro_name"] not in ["pop-os", "generic"] and not skip_de_selection:
103 | de_list = ["Gnome", "KDE", "Xfce", "LXQt", "Cinnamon"]
104 | flags_list = [f"(recommended) +{os_sizes[temp_distro_name]['gnome']}GB",
105 | f"(recommended) +{os_sizes[temp_distro_name]['kde']}GB",
106 | f"(recommended for slow devices) +{os_sizes[temp_distro_name]['xfce']}GB",
107 | f"(recommended for slow devices) +{os_sizes[temp_distro_name]['lxqt']}GB",
108 | f"+{os_sizes[temp_distro_name]['cinnamon']}GB"]
109 | match output_dict["distro_name"]:
110 | case "ubuntu":
111 | if output_dict["distro_version"] == "22.04":
112 | de_list.append("Deepin")
113 | flags_list.append(f"+{os_sizes[temp_distro_name]['deepin']}GB")
114 | de_list.append("Budgie")
115 | flags_list.append(f"+{os_sizes[temp_distro_name]['budgie']}GB")
116 | case "arch":
117 | de_list.extend(["Deepin", "Budgie"])
118 | flags_list.append(f"+{os_sizes[temp_distro_name]['deepin']}GB")
119 | flags_list.append(f"+{os_sizes[temp_distro_name]['budgie']}GB")
120 | case "debian":
121 | de_list.append("Budgie")
122 | flags_list.append(f"+{os_sizes[temp_distro_name]['budgie']}GB")
123 | case "fedora":
124 | de_list.extend(["Deepin", "Budgie"])
125 | flags_list.append(f"+{os_sizes[temp_distro_name]['deepin']}GB")
126 | flags_list.append(f"+{os_sizes[temp_distro_name]['budgie']}GB")
127 |
128 | de_list.append("cli") # add at the end for better ux
129 | flags_list.append(f"+0GB") # cli doesn't need additional space
130 |
131 | while True:
132 | desktop_env = ia_selection("Which desktop environment (Desktop GUI) would you like to use?",
133 | options=de_list,
134 | flags=flags_list)
135 | if desktop_env == "cli":
136 | print_warning("Warning: No desktop environment will be installed!")
137 | if verbose_kernel:
138 | print_error("High verbosity kernel messages will print to TTY making it practically unusable.")
139 | print_header("If you plan to install an unsupported desktop environment, make sure to specify it "
140 | "in /etc/eupnea.json after installation. Consider making a pr with support for this DE.")
141 | user_selection = ia_selection("Are you sure you want to continue?", options=["No", "Yes"], )
142 | if user_selection == "No":
143 | print_status("No desktop will be installed.")
144 | continue
145 |
146 | output_dict["de_name"] = desktop_env.lower()
147 | break
148 | elif output_dict["distro_name"] == "pop-os":
149 | output_dict["de_name"] = "cosmic-gnome"
150 |
151 | while True:
152 | kernel_type = ia_selection("Which kernel type would you like to use? \nYou can change kernels "
153 | "post-install by installing the eupnea-chromeos-kernel or eupnea-mainline-kernel "
154 | "package with your package manager.",
155 | options=["Mainline", "ChromeOS"],
156 | flags=["(default, recommended)"])
157 |
158 | output_dict["kernel_type"] = kernel_type.lower()
159 | break
160 |
161 | print_question("Enter a username for the new user")
162 | while True:
163 | output_dict["username"] = input("\033[94m" + "Username (default: 'localuser'): " + "\033[0m")
164 | if output_dict["username"] == "":
165 | print("Using 'localuser' as username")
166 | output_dict["username"] = "localuser"
167 | break
168 | found_invalid_char = False
169 | for char in output_dict["username"]:
170 | if char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-":
171 | print_warning(f"Username contains invalid character: {char}")
172 | found_invalid_char = True
173 | break
174 | if not found_invalid_char:
175 | break
176 |
177 | print_question("Please set a secure password")
178 | while True:
179 | passwd_temp = getpass("\033[94m" + "Password: " + "\033[0m")
180 | if passwd_temp == "":
181 | print_warning("Password cannot be empty")
182 | continue
183 |
184 | else:
185 | passwd_temp_repeat = getpass("\033[94m" + "Repeat password: " + "\033[0m")
186 | if passwd_temp == passwd_temp_repeat:
187 | output_dict["password"] = passwd_temp
188 | break
189 | else:
190 | print_warning("Passwords do not match, please try again")
191 | continue
192 |
193 | # Check if usb reading is possible
194 | if not path_exists("/sys/dev/block"):
195 | print_warning("Couldn't read usb devices. Building image file.")
196 | skip_device = True
197 |
198 | if not skip_device:
199 | print_status("Available devices: ")
200 | usb_array = []
201 | usb_info_array = []
202 | lsblk_out = bash("lsblk -nd -o NAME,MODEL,SIZE,TRAN").splitlines()
203 | for line in lsblk_out:
204 | if line.find("usb") != -1 and line.find("0B") == -1: # Print USB devices only with storage more than 0B
205 | usb_array.append(line[:3])
206 | usb_info_array.append(line[3:])
207 | if not usb_array:
208 | print_status("No available USBs/SD-cards found. Building image file.")
209 | else:
210 | device = ia_selection("Select USB-drive/SD-card name or 'image' to build an image",
211 | options=usb_array + ["image"],
212 | flags=usb_info_array + ["Build image instead of writing to USB/SD-card directly"])
213 | if device == "image":
214 | print("Building image instead of writing directly")
215 | else:
216 | print(f"Writing directly to {device}")
217 | output_dict["device"] = device
218 |
219 | print_status("User input complete")
220 | return output_dict
221 |
222 |
223 | class KeyGetter:
224 | def arm(self):
225 | self.old_term = termios.tcgetattr(sys.stdin)
226 | tty.setcbreak(sys.stdin)
227 |
228 | atexit.register(self.disarm)
229 |
230 | def disarm(self):
231 | termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_term)
232 |
233 | def getch(self):
234 | self.arm()
235 | ch = sys.stdin.read(1)[0]
236 | self.disarm()
237 | return ch
238 |
239 |
240 | def ia_selection(question: str, options: list = None, flags: list = None) -> str:
241 | print_question(question)
242 | return _draw_ia_selection(options, flags)
243 |
244 |
245 | def _draw_ia_selection(options: list, flags: list = None):
246 | __UNPOINTED = " "
247 | __POINTED = ">"
248 | __INDEX = 0
249 | __LENGTH = len(options)
250 | __ARROWS = __UP, _ = 65, 66
251 | __ENTER = 10
252 |
253 | if flags is None:
254 | flags = []
255 |
256 | def _choices_print():
257 | for i, (option, flag) in enumerate(zip_longest(options, flags, fillvalue='')):
258 | if i == __INDEX:
259 | print(f" {__POINTED} {{0}}{option} {flag}{{1}}".format('\033[94m', '\033[0m'))
260 | else:
261 | print(f" {__UNPOINTED} {option} {flag}")
262 |
263 | def _choices_clear():
264 | print(f"\033[{__LENGTH}A\033[J", end='')
265 |
266 | def _move_pointer(ch_ord: int):
267 | nonlocal __INDEX
268 | __INDEX = max(0, __INDEX - 1) if ch_ord == __UP else min(__INDEX + 1, __LENGTH - 1)
269 |
270 | def _main_loop():
271 | kg = KeyGetter()
272 | _choices_print()
273 | while True:
274 | key = ord(kg.getch())
275 | if key in __ARROWS:
276 | _move_pointer(key)
277 | _choices_clear()
278 | _choices_print()
279 | if key == __ENTER:
280 | _choices_clear()
281 | _choices_print()
282 | break
283 |
284 | _main_loop()
285 | return options[__INDEX]
286 |
--------------------------------------------------------------------------------
/configs/crostini/devices.allow:
--------------------------------------------------------------------------------
1 | c *:* rwm
2 | b *:* rwm
3 |
--------------------------------------------------------------------------------
/configs/crostini/setup-crostini.sh:
--------------------------------------------------------------------------------
1 | mount -t devtmpfs /dev /dev
2 | ln -sf /proc/self/fd /dev/
3 | cd /sys/fs/cgroup/
4 | if [ ! -d devices ]; then
5 | mkdir -p devices
6 | mount -t cgroup cgroup /sys/fs/cgroup/devices/ -o rw,nosuid,nodev,noexec,relatime,devices
7 | fi
8 | printf '%s\n' 'c *:* rwm' 'b *:* rwm' > devices/devices.allow
--------------------------------------------------------------------------------
/configs/debian-sources.list:
--------------------------------------------------------------------------------
1 | # main debian repository
2 | deb http://deb.debian.org/debian stable main non-free-firmware non-free
3 |
4 | # security repository
5 | deb http://security.debian.org/debian-security stable-security main non-free-firmware non-free
6 |
7 | # updates repository
8 | deb http://deb.debian.org/debian/ stable-updates main non-free-firmware non-free
--------------------------------------------------------------------------------
/configs/eupnea.json:
--------------------------------------------------------------------------------
1 | {
2 | "depthboot_version": "1.4.0",
3 | "install_type": "image",
4 | "distro_name": "",
5 | "distro_version": "",
6 | "de_name": "",
7 | "firmware_payload": "depthcharge"
8 | }
9 |
--------------------------------------------------------------------------------
/configs/selinux/fixfiles:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # SOURCE: https://github.com/SELinuxProject/selinux/blob/master/policycoreutils/scripts/fixfiles
4 |
5 | # fixfiles
6 | #
7 | # Script to restore labels on a SELinux box
8 | #
9 | # Copyright (C) 2004-2013 Red Hat, Inc.
10 | # Authors: Dan Walsh
11 | #
12 | # This program is free software; you can redistribute it and/or modify
13 | # it under the terms of the GNU General Public License as published by
14 | # the Free Software Foundation; either version 2 of the License, or
15 | # (at your option) any later version.
16 | #
17 | # This program is distributed in the hope that it will be useful,
18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 | # GNU General Public License for more details.
21 | #
22 | # You should have received a copy of the GNU General Public License
23 | # along with this program; if not, write to the Free Software
24 | # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 | #
26 | # Slightly modified by Apacelus, The Eupnea Project
27 |
28 | set -o nounset
29 |
30 | #
31 | # seclabel support was added in 2.6.30. This function will return a positive
32 | # number if the current kernel version is greater than 2.6.30, a negative
33 | # number if the current is less than 2.6.30 and 0 if they are the same.
34 | #
35 | function useseclabel {
36 | VER=`uname -r`
37 | SUP=2.6.30
38 | expr '(' "$VER" : '\([^.]*\)' ')' '-' '(' "$SUP" : '\([^.]*\)' ')' '|' \
39 | '(' "$VER.0" : '[^.]*[.]\([^.]*\)' ')' '-' '(' "$SUP.0" : '[^.]*[.]\([^.]*\)' ')' '|' \
40 | '(' "$VER.0.0" : '[^.]*[.][^.]*[.]\([^.]*\)' ')' '-' '(' "$SUP.0.0" : '[^.]*[.][^.]*[.]\([^.]*\)' ')'
41 | }
42 |
43 | #
44 | # Get all mount points that support labeling. Use the 'seclabel' field if it
45 | # is available. Else fall back to known fs types which likely support xattrs
46 | # and we know were not context mounted.
47 | #
48 | get_all_labeled_mounts() {
49 | FS="`cat /proc/self/mounts | sort | uniq | awk '{print $2}'`"
50 | for i in $FS; do
51 | if [ `useseclabel` -ge 0 ]
52 | then
53 | grep " $i " /proc/self/mounts | awk '{print $4}' | grep -E --silent '(^|,)seclabel(,|$)' && echo $i
54 | else
55 | grep " $i " /proc/self/mounts | grep -v "context=" | grep -E --silent '(ext[234]| ext4dev | gfs2 | xfs | jfs | btrfs )' && echo $i
56 | fi
57 | done
58 | }
59 |
60 | get_rw_labeled_mounts() {
61 | FS=`get_all_labeled_mounts | sort | uniq`
62 | for i in $FS; do
63 | grep " $i " /proc/self/mounts | awk '{print $4}' | grep -E --silent '(^|,)rw(,|$)' && echo $i
64 | done
65 | }
66 |
67 | get_ro_labeled_mounts() {
68 | FS=`get_all_labeled_mounts | sort | uniq`
69 | for i in $FS; do
70 | grep " $i " /proc/self/mounts | awk '{print $4}' | grep -E --silent '(^|,)ro(,|$)' && echo $i
71 | done
72 | }
73 |
74 | #
75 | # Get the default label returned from the kernel for a file with a label the
76 | # kernel does not understand
77 | #
78 | get_undefined_type() {
79 | SELINUXMNT=`grep selinuxfs /proc/self/mountinfo | head -1 | awk '{ print $5 }'`
80 | cat ${SELINUXMNT}/initial_contexts/unlabeled | secon -t
81 | }
82 |
83 | #
84 | # Get the default label for a file without a label
85 | #
86 | get_unlabeled_type() {
87 | SELINUXMNT=`grep selinuxfs /proc/self/mountinfo | head -1 | awk '{ print $5 }'`
88 | cat $SELINUXMNT/initial_contexts/file | secon -t
89 | }
90 |
91 | exclude_dirs_from_relabelling() {
92 | exclude_from_relabelling=
93 | if [ -e /etc/selinux/fixfiles_exclude_dirs ]
94 | then
95 | while read i
96 | do
97 | # skip blank line and comment
98 | # skip not absolute path
99 | # skip not directory
100 | [ -z "${i}" ] && continue
101 | [[ "${i}" =~ ^[[:blank:]]*# ]] && continue
102 | [[ ! "${i}" =~ ^/.* ]] && continue
103 | [[ ! -d "${i}" ]] && continue
104 | exclude_from_relabelling="$exclude_from_relabelling -e $i"
105 | done < /etc/selinux/fixfiles_exclude_dirs
106 | fi
107 | echo "$exclude_from_relabelling"
108 | }
109 |
110 | #
111 | # Set global Variables
112 | #
113 | fullFlag=0
114 | BOOTTIME=""
115 | VERBOSE="-p"
116 | FORCEFLAG=""
117 | THREADS=""
118 | RPMFILES=""
119 | PREFC=""
120 | RESTORE_MODE=""
121 | BIND_MOUNT_FILESYSTEMS=""
122 | SETFILES=/sbin/setfiles
123 | RESTORECON=/sbin/restorecon
124 | FILESYSTEMSRW=`get_rw_labeled_mounts`
125 | FILESYSTEMSRO=`get_ro_labeled_mounts`
126 | SELINUXTYPE="targeted"
127 | if [ -e /etc/selinux/config ]; then
128 | . /etc/selinux/config
129 | FC=/etc/selinux/${SELINUXTYPE}/contexts/files/file_contexts
130 | else
131 | FC=/etc/security/selinux/file_contexts
132 | fi
133 |
134 | #
135 | # Log all Read Only file systems
136 | #
137 | LogReadOnly() {
138 | if [ ! -z "$FILESYSTEMSRO" ]; then
139 | echo "Warning: Skipping the following R/O filesystems:"
140 | echo "$FILESYSTEMSRO"
141 | fi
142 | }
143 |
144 | #
145 | # Log directories excluded from relabelling by configuration file
146 | #
147 | LogExcluded() {
148 | for i in ${EXCLUDEDIRS//-e / }; do
149 | echo "skipping the directory $i"
150 | done
151 | }
152 |
153 | #
154 | # Find files newer then the passed in date and fix the label
155 | #
156 | newer() {
157 | DATE=$1
158 | shift
159 | LogReadOnly
160 | for m in `echo $FILESYSTEMSRW`; do
161 | find $m -mount -newermt $DATE -print0 2>/dev/null | ${RESTORECON} ${FORCEFLAG} ${VERBOSE} ${THREADS} $* -i -0 -f -
162 | done;
163 | }
164 |
165 | #
166 | # Compare PREVious File Context to currently installed File Context and
167 | # run restorecon on all files affected by the differences.
168 | #
169 | diff_filecontext() {
170 | EXCLUDEDIRS="`exclude_dirs_from_relabelling`"
171 | for i in /sys /proc /mnt /var/tmp /var/lib/BackupPC /home /root /tmp; do
172 | [ -e $i ] && EXCLUDEDIRS="${EXCLUDEDIRS} -e $i";
173 | done
174 | LogExcluded
175 |
176 | if [ -f ${PREFC} -a -x /usr/bin/diff ]; then
177 | TEMPFILE=`mktemp ${FC}.XXXXXXXXXX`
178 | test -z "$TEMPFILE" && exit
179 | PREFCTEMPFILE=`mktemp ${PREFC}.XXXXXXXXXX`
180 | sed -r -e 's,:s0, ,g' $PREFC | sort -u > ${PREFCTEMPFILE}
181 | sed -r -e 's,:s0, ,g' $FC | sort -u | \
182 | /usr/bin/diff -b ${PREFCTEMPFILE} - | \
183 | grep '^[<>]'|cut -c3-| grep ^/ | \
184 | grep -Ev '(^/home|^/root|^/tmp)' |\
185 | sed -r -e 's,[[:blank:]].*,,g' \
186 | -e 's|\(([/[:alnum:]]+)\)\?|{\1,}|g' \
187 | -e 's|([/[:alnum:]])\?|{\1,}|g' \
188 | -e 's|\?.*|*|g' \
189 | -e 's|\{.*|*|g' \
190 | -e 's|\(.*|*|g' \
191 | -e 's|\[.*|*|g' \
192 | -e 's|\.\*.*|*|g' \
193 | -e 's|\.\+.*|*|g' | \
194 | # These two sorts need to be separate commands \
195 | sort -u | \
196 | sort -d | \
197 | while read pattern ; \
198 | do if ! echo "$pattern" | grep -q -f ${TEMPFILE} 2>/dev/null; then \
199 | echo "$pattern"; \
200 | case "$pattern" in *"*") \
201 | echo "$pattern" | sed -e 's,^,^,' -e 's,\*$,,g' >> ${TEMPFILE};;
202 | esac; \
203 | fi; \
204 | done | \
205 | ${RESTORECON} ${VERBOSE} ${EXCLUDEDIRS} ${FORCEFLAG} ${THREADS} $* -i -R -f -; \
206 | rm -f ${TEMPFILE} ${PREFCTEMPFILE}
207 | fi
208 | }
209 |
210 | rpmlist() {
211 | rpm -q --qf '[%{FILESTATES} %{FILENAMES}\n]' "$1" | grep '^0 ' | cut -f2- -d ' '
212 | [ ${PIPESTATUS[0]} != 0 ] && echo "$1 not found" >/dev/stderr
213 | }
214 |
215 | # unmount tmp bind mount before exit
216 | umount_TMP_MOUNT() {
217 | if [ -n "$TMP_MOUNT" ]; then
218 | umount "${TMP_MOUNT}${m}" || exit 130
219 | rm -rf "${TMP_MOUNT}" || echo "Error cleaning up."
220 | fi
221 | exit 130
222 | }
223 |
224 | fix_labels_on_mountpoint() {
225 | test -z ${TMP_MOUNT+x} && echo "Unable to find temporary directory!" && exit 1
226 | mkdir -p "${TMP_MOUNT}${m}" || exit 1
227 | mount --bind "${m}" "${TMP_MOUNT}${m}" || exit 1
228 | ${SETFILES} ${VERBOSE} ${EXCLUDEDIRS} ${FORCEFLAG} ${THREADS} $* -q ${FC} -r "${TMP_MOUNT}" "${TMP_MOUNT}${m}"
229 | umount "${TMP_MOUNT}${m}" || exit 1
230 | rm -rf "${TMP_MOUNT}" || echo "Error cleaning up."
231 | }
232 | export -f fix_labels_on_mountpoint
233 |
234 | #
235 | # restore
236 | # if called with -n will only check file context
237 | #
238 | restore () {
239 | OPTION=$1
240 | shift
241 |
242 | # [-B | -N time ]
243 | if [ -n "$BOOTTIME" ]; then
244 | newer $BOOTTIME $*
245 | return
246 | fi
247 |
248 | # -C PREVIOUS_FILECONTEXT
249 | if [ "$RESTORE_MODE" == PREFC ]; then
250 | diff_filecontext $*
251 | return
252 | fi
253 |
254 | [ -x /usr/sbin/genhomedircon ] && /usr/sbin/genhomedircon
255 |
256 | EXCLUDEDIRS="`exclude_dirs_from_relabelling`"
257 | LogExcluded
258 |
259 | case "$RESTORE_MODE" in
260 | RPMFILES)
261 | for i in `echo "$RPMFILES" | sed 's/,/ /g'`; do
262 | rpmlist $i | ${RESTORECON} ${VERBOSE} ${EXCLUDEDIRS} ${FORCEFLAG} ${THREADS} $* -i -R -f -
263 | done
264 | ;;
265 | FILEPATH)
266 | ${RESTORECON} ${VERBOSE} ${EXCLUDEDIRS} ${FORCEFLAG} ${THREADS} $* -R -- "$FILEPATH"
267 | ;;
268 | *)
269 | if [ -n "${FILESYSTEMSRW}" ]; then
270 | LogReadOnly
271 | echo "${OPTION}ing `echo ${FILESYSTEMSRW}`"
272 |
273 | if [ -z "$BIND_MOUNT_FILESYSTEMS" ]; then
274 | ${SETFILES} ${VERBOSE} ${EXCLUDEDIRS} ${FORCEFLAG} $* -q ${THREADS} ${FC} ${FILESYSTEMSRW}
275 | else
276 | # we bind mount so we can fix the labels of files that have already been
277 | # mounted over
278 | for m in `echo $FILESYSTEMSRW`; do
279 | TMP_MOUNT="$(mktemp -p /run -d fixfiles.XXXXXXXXXX)"
280 | export SETFILES VERBOSE EXCLUDEDIRS FORCEFLAG THREADS FC TMP_MOUNT m
281 | if type unshare &> /dev/null; then
282 | unshare -m bash -c "fix_labels_on_mountpoint $*" || exit $?
283 | else
284 | trap umount_TMP_MOUNT EXIT
285 | fix_labels_on_mountpoint $*
286 | trap EXIT
287 | fi
288 | done;
289 | fi
290 | else
291 | echo >&2 "fixfiles: No suitable file systems found"
292 | fi
293 | if [ ${OPTION} != "Relabel" ]; then
294 | return
295 | fi
296 | echo "Cleaning up labels on /tmp"
297 | rm -rf /tmp/gconfd-* /tmp/pulse-* /tmp/orbit-*
298 | # The 2 lines below are changed to run this script in chroots
299 | UNDEFINED="unlabeled_t"
300 | UNLABELED="unlabeled_t"
301 | find /tmp \( -context "*:${UNLABELED}*" -o -context "*:${UNDEFINED}*" \) \( -type s -o -type p \) -delete
302 | find /tmp \( -context "*:${UNLABELED}*" -o -context "*:${UNDEFINED}*" \) -exec chcon --no-dereference --reference /tmp {} \;
303 | find /var/tmp \( -context "*:${UNLABELED}*" -o -context "*:${UNDEFINED}*" \) -exec chcon --no-dereference --reference /var/tmp {} \;
304 | find /var/run \( -context "*:${UNLABELED}*" -o -context "*:${UNDEFINED}*" \) -exec chcon --no-dereference --reference /var/run {} \;
305 | [ ! -e /var/lib/debug ] || find /var/lib/debug \( -context "*:${UNLABELED}*" -o -context "*:${UNDEFINED}*" \) -exec chcon --no-dereference --reference /lib {} \;
306 | ;;
307 | esac
308 | }
309 |
310 | fullrelabel() {
311 | echo "Cleaning out /tmp"
312 | find /tmp/ -mindepth 1 -delete
313 | restore Relabel
314 | }
315 |
316 |
317 | relabel() {
318 | if [ -n "$RESTORE_MODE" -a "$RESTORE_MODE" != DEFAULT ]; then
319 | usage
320 | exit 1
321 | fi
322 |
323 | if [ $fullFlag == 1 ]; then
324 | fullrelabel
325 | return
326 | fi
327 |
328 | echo -n "
329 | Files in the /tmp directory may be labeled incorrectly, this command
330 | can remove all files in /tmp. If you choose to remove files from /tmp,
331 | a reboot will be required after completion.
332 |
333 | Do you wish to clean out the /tmp directory [N]? "
334 | read answer
335 | if [ "$answer" = y -o "$answer" = Y ]; then
336 | fullrelabel
337 | else
338 | restore Relabel
339 | fi
340 | }
341 |
342 | process() {
343 | #
344 | # Make sure they specified one of the three valid commands
345 | #
346 | case "$1" in
347 | restore) restore Relabel;;
348 | check) VERBOSE="-v"; restore Check -n;;
349 | verify) VERBOSE="-v"; restore Verify -n;;
350 | relabel) relabel;;
351 | onboot)
352 | if [ -n "$RESTORE_MODE" -a "$RESTORE_MODE" != DEFAULT ]; then
353 | usage
354 | exit 1
355 | fi
356 | > /.autorelabel || exit $?
357 | [ -z "$FORCEFLAG" ] || echo -n "$FORCEFLAG " >> /.autorelabel
358 | [ -z "$BOOTTIME" ] || echo -n "-N $BOOTTIME " >> /.autorelabel
359 | [ -z "$BIND_MOUNT_FILESYSTEMS" ] || echo -n "-M " >> /.autorelabel
360 | [ -z "$THREADS" ] || echo -n "$THREADS " >> /.autorelabel
361 | # Force full relabel if SELinux is not enabled
362 | selinuxenabled || echo -F > /.autorelabel
363 | echo "System will relabel on next boot"
364 | ;;
365 | *)
366 | usage
367 | exit 1
368 | esac
369 | }
370 | usage() {
371 | echo $"""
372 | Usage: $0 [-v] [-F] [-M] [-f] [-T nthreads] relabel
373 | or
374 | Usage: $0 [-v] [-F] [-B | -N time ] [-T nthreads] { check | restore | verify }
375 | or
376 | Usage: $0 [-v] [-F] [-T nthreads] { check | restore | verify } dir/file ...
377 | or
378 | Usage: $0 [-v] [-F] [-T nthreads] -R rpmpackage[,rpmpackage...] { check | restore | verify }
379 | or
380 | Usage: $0 [-v] [-F] [-T nthreads] -C PREVIOUS_FILECONTEXT { check | restore | verify }
381 | or
382 | Usage: $0 [-F] [-M] [-B] [-T nthreads] onboot
383 | """
384 | }
385 |
386 | if [ $# -eq 0 ]; then
387 | usage
388 | exit 1
389 | fi
390 |
391 | set_restore_mode() {
392 | if [ -n "$RESTORE_MODE" ]; then
393 | # can't specify two different modes
394 | usage
395 | exit 1
396 | fi
397 | RESTORE_MODE="$1"
398 | }
399 |
400 | # See how we were called.
401 | while getopts "N:BC:FfR:l:vMT:" i; do
402 | case "$i" in
403 | B)
404 | BOOTTIME=`/bin/who -b | awk '{print $3}'`
405 | set_restore_mode DEFAULT
406 | ;;
407 | N)
408 | BOOTTIME=$OPTARG
409 | set_restore_mode BOOTTIME
410 | ;;
411 | R)
412 | RPMFILES=$OPTARG
413 | set_restore_mode RPMFILES
414 | ;;
415 | C)
416 | PREFC=$OPTARG
417 | set_restore_mode PREFC
418 | ;;
419 | v)
420 | VERBOSE="-v"
421 | ;;
422 | l)
423 | # Old scripts use obsolete option `-l logfile`
424 | echo "Redirecting output to $OPTARG"
425 | exec >>"$OPTARG" 2>&1
426 | ;;
427 | M)
428 | BIND_MOUNT_FILESYSTEMS="-M"
429 | ;;
430 | F)
431 | FORCEFLAG="-F"
432 | ;;
433 | f)
434 | fullFlag=1
435 | ;;
436 | T)
437 | THREADS="-T $OPTARG"
438 | ;;
439 | *)
440 | usage
441 | exit 1
442 | esac
443 | done
444 | # Move out processed options from arguments
445 | shift $(( OPTIND - 1 ))
446 |
447 | # Check for the command
448 | if [ $# -eq 0 ]; then
449 | usage
450 | exit 1
451 | fi
452 | command="$1"
453 |
454 | # Move out command from arguments
455 | shift
456 |
457 | if [ $# -gt 0 ]; then
458 | set_restore_mode FILEPATH
459 | while [ $# -gt 0 ]; do
460 | FILEPATH="$1"
461 | process "$command" || exit $?
462 | shift
463 | done
464 | else
465 | process "$command"
466 | fi
467 |
468 |
--------------------------------------------------------------------------------
/configs/selinux/mountinfo:
--------------------------------------------------------------------------------
1 | 23 1 8:2 / / rw,relatime shared:1 - ext4 /dev/root rw,seclabel
2 | 24 23 0:5 / /dev rw,nosuid,noexec,relatime shared:2 - devtmpfs devtmpfs rw,seclabel,size=1976988k,nr_inodes=494247,mode=755
3 | 25 23 0:22 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw
4 | 26 23 0:23 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw,seclabel
5 | 27 26 0:6 / /sys/kernel/security rw,nosuid,nodev,noexec,relatime shared:7 - securityfs securityfs rw
6 | 29 26 0:18 / /sys/fs/selinux rw,nosuid,noexec,relatime shared:8 - selinuxfs selinuxfs rw
7 | 28 24 0:24 / /dev/shm rw,nosuid,nodev shared:3 - tmpfs tmpfs rw,seclabel
8 | 30 24 0:25 / /dev/pts rw,nosuid,noexec,relatime shared:4 - devpts devpts rw,seclabel,gid=5,mode=620,ptmxmode=000
9 | 31 23 0:26 / /run rw,nosuid,nodev shared:12 - tmpfs tmpfs rw,seclabel,size=792160k,nr_inodes=819200,mode=755
10 | 32 26 0:27 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime shared:9 - cgroup2 cgroup2 rw,seclabel,nsdelegate,memory_recursiveprot
11 | 33 26 0:28 / /sys/fs/pstore rw,nosuid,nodev,noexec,relatime shared:10 - pstore pstore rw,seclabel
12 | 34 26 0:29 / /sys/fs/bpf rw,nosuid,nodev,noexec,relatime shared:11 - bpf none rw,mode=700
13 | 35 25 0:30 / /proc/sys/fs/binfmt_misc rw,relatime shared:13 - autofs systemd-1 rw,fd=29,pgrp=1,timeout=0,minproto=5,maxproto=5,direct
14 | 36 24 0:31 / /dev/hugepages rw,relatime shared:14 - hugetlbfs hugetlbfs rw,seclabel,pagesize=2M
15 | 37 24 0:17 / /dev/mqueue rw,nosuid,nodev,noexec,relatime shared:15 - mqueue mqueue rw,seclabel
16 | 38 26 0:7 / /sys/kernel/debug rw,nosuid,nodev,noexec,relatime shared:16 - debugfs debugfs rw,seclabel
17 | 39 23 0:32 / /tmp rw,nosuid,nodev shared:17 - tmpfs tmpfs rw,seclabel,size=1980400k,nr_inodes=1048576
18 | 40 26 0:10 / /sys/kernel/tracing rw,nosuid,nodev,noexec,relatime shared:18 - tracefs tracefs rw,seclabel
19 | 41 26 0:33 / /sys/fs/fuse/connections rw,nosuid,nodev,noexec,relatime shared:19 - fusectl fusectl rw
20 | 42 26 0:21 / /sys/kernel/config rw,nosuid,nodev,noexec,relatime shared:20 - configfs configfs rw
21 | 129 23 0:34 / /var/lib/nfs/rpc_pipefs rw,relatime shared:43 - rpc_pipefs sunrpc rw
22 | 790 31 0:48 / /run/user/1000 rw,nosuid,nodev,relatime shared:439 - tmpfs tmpfs rw,seclabel,size=396076k,nr_inodes=99019,mode=700,uid=1000,gid=1000
23 |
--------------------------------------------------------------------------------
/configs/selinux/mounts:
--------------------------------------------------------------------------------
1 | /dev/root / ext4 rw,seclabel,relatime 0 0
2 | devtmpfs /dev devtmpfs rw,seclabel,nosuid,noexec,relatime,size=1976988k,nr_inodes=494247,mode=755 0 0
3 | proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0
4 | sysfs /sys sysfs rw,seclabel,nosuid,nodev,noexec,relatime 0 0
5 | securityfs /sys/kernel/security securityfs rw,nosuid,nodev,noexec,relatime 0 0
6 | selinuxfs /sys/fs/selinux selinuxfs rw,nosuid,noexec,relatime 0 0
7 | devpts /dev/pts devpts rw,seclabel,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000 0 0
8 | tmpfs /run tmpfs rw,seclabel,nosuid,nodev,size=792160k,nr_inodes=819200,mode=755 0 0
9 | none /sys/fs/bpf bpf rw,nosuid,nodev,noexec,relatime,mode=700 0 0
10 | systemd-1 /proc/sys/fs/binfmt_misc autofs rw,relatime,fd=29,pgrp=1,timeout=0,minproto=5,maxproto=5,direct 0 0
11 | tmpfs /tmp tmpfs rw,seclabel,nosuid,nodev,size=1980400k,nr_inodes=1048576 0 0
12 | fusectl /sys/fs/fuse/connections fusectl rw,nosuid,nodev,noexec,relatime 0 0
13 | configfs /sys/kernel/config configfs rw,nosuid,nodev,noexec,relatime 0 0
14 | sunrpc /var/lib/nfs/rpc_pipefs rpc_pipefs rw,relatime 0 0
--------------------------------------------------------------------------------
/configs/selinux/unlabeled:
--------------------------------------------------------------------------------
1 | system_u:object_r:unlabeled_t:s0
--------------------------------------------------------------------------------
/configs/zram/zram-generator.conf:
--------------------------------------------------------------------------------
1 | # This file is part of the zram-generator project
2 | # https://github.com/systemd/zram-generator
3 |
4 | [zram0]
5 | # This section describes the settings for /dev/zram0.
6 | #
7 | # The maximum amount of memory (in MiB). If the machine has more RAM
8 | # than this, zram device will not be created.
9 | #
10 | # "host-memory-limit = none" may be used to disable this limit. This
11 | # is also the default.
12 | host-memory-limit = none
13 |
14 | # The fraction of memory to use as ZRAM. For example, if the machine
15 | # has 1 GiB, and zram-fraction=0.25, then the zram device will have
16 | # 256 MiB. Values in the range 0.10–0.50 are recommended.
17 | #
18 | # The default is 0.5.
19 | zram-fraction = 0.5
20 |
21 | # The maximum size of the zram device (in MiB).
22 | #
23 | # If host-memory times zram-fraction is greater than this,
24 | # the size will be capped to this amount;
25 | # for example, on a machine with 2 GiB of RAM and with zram-fraction=0.5,
26 | # the device would still be 512 MiB in size due to the limit below.
27 | #
28 | # The default is 4096.
29 | # max-zram-size = 4096
30 |
31 | # The compression algorithm to use for the zram device,
32 | # or leave unspecified to keep the kernel default.
33 | compression-algorithm = lzo-rle
34 |
35 | #[zram1]
36 | # This section describes the settings for /dev/zram1.
37 | #
38 | # host-memory-limit is not specifed, so this device will always be created.
39 |
40 | # Size the device to a tenth of RAM.
41 | #zram-fraction = 0.1
42 |
43 | # The file system to put on the device. If not specified, ext2 will be used.
44 | #fs-type = ext2
45 |
46 | # Where to mount the file system. If a mount point is not specified,
47 | # the device will be initialized, but will not be used for anything.
48 | # mount-point = /run/compressed-mount-point
--------------------------------------------------------------------------------
/distro/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/eupnea-project/depthboot-builder/f2a2dc4579d66c946adce0aae12b5babd02efaba/distro/__init__.py
--------------------------------------------------------------------------------
/distro/arch.py:
--------------------------------------------------------------------------------
1 | from functions import *
2 |
3 | # --needed: only install packages that are not already installed
4 | # --disable-download-timeout: disable download timeout, as it often triggers, even when downloading
5 | # via a stable connection from GitHub
6 | pacman_command = "pacman -S --noconfirm --disable-download-timeout"
7 |
8 |
9 | def config(de_name: str, distro_version: str, verbose: bool, kernel_version: str) -> None:
10 | set_verbose(verbose)
11 | print_status("Configuring Arch")
12 |
13 | # Uncomment worldwide arch mirror
14 | with open("/mnt/depthboot/etc/pacman.d/mirrorlist", "r") as read:
15 | mirrors = read.readlines()
16 | # Uncomment first mirror
17 | mirrors[6] = mirrors[6][1:]
18 | with open("/mnt/depthboot/etc/pacman.d/mirrorlist", "w") as write:
19 | write.writelines(mirrors)
20 |
21 | # temporarily comment out CheckSpace, coz Pacman fails to check available storage space when run from a chroot
22 | with open("/mnt/depthboot/etc/pacman.conf", "r") as conf:
23 | temp_pacman = conf.readlines()
24 | temp_pacman[34] = f"#{temp_pacman[34]}"
25 | with open("/mnt/depthboot/etc/pacman.conf", "w") as conf:
26 | conf.writelines(temp_pacman)
27 |
28 | print_status("Preparing pacman")
29 | chroot("pacman-key --init") # create local master key
30 | chroot("pacman-key --populate archlinux") # add archlinux keys
31 | # add eupnea key
32 | urlretrieve("https://eupnea-project.github.io/pkg-repo/public_key.gpg", filename="/mnt/depthboot/tmp/eupnea.key")
33 | chroot("pacman-key --add /tmp/eupnea.key")
34 | chroot("pacman-key --lsign-key 4F8A31EAADF1588D0B45A0DAAC87331A20A7250A")
35 | # add repo to pacman.conf
36 | with open("/mnt/depthboot/etc/pacman.conf", "a") as file:
37 | file.write("[eupnea]\nServer = https://eupnea-project.github.io/pkg-repo/repodata/$arch\n")
38 | chroot(f"{pacman_command} -yyu") # refresh all repos update the whole system
39 |
40 | print_status("Installing packages")
41 | # Install basic utils. Do not reinstall if already installed
42 | chroot(f"{pacman_command} --needed base base-devel nano networkmanager xkeyboard-config linux-firmware sudo bluez "
43 | f"bluez-utils python3 cgpt-vboot-utils zram-generator")
44 | # install eupnea packages after installing python3
45 | chroot(f"{pacman_command} eupnea-utils eupnea-system")
46 | # Install kernel
47 | chroot(f"{pacman_command} eupnea-{kernel_version}-kernel")
48 |
49 | print_status("Downloading and installing de, might take a while")
50 | match de_name:
51 | case "gnome":
52 | print_status("Installing GNOME")
53 | chroot(f"{pacman_command} gnome gnome-extra")
54 | chroot("systemctl enable gdm.service")
55 | case "kde":
56 | print_status("Installing KDE")
57 | chroot(f"{pacman_command} plasma-meta plasma-wayland-session kde-system-meta kde-utilities-meta "
58 | "packagekit-qt5 firefox")
59 | chroot("systemctl enable sddm.service")
60 | # Set default kde sddm theme
61 | mkdir("/mnt/depthboot/etc/sddm.conf.d")
62 | with open("/mnt/depthboot/etc/sddm.conf.d/breeze-theme.conf", "a") as conf:
63 | conf.write("[Theme]\nCurrent=breeze")
64 | case "xfce":
65 | print_status("Installing Xfce")
66 | # xfce doesn't have its own audio settings and therefore needs pavucontrol
67 | # xfce does not have any audio servers as dependencies -> manually install pipewire
68 | chroot(f"{pacman_command} xfce4 xfce4-goodies xorg xorg-server lightdm lightdm-gtk-greeter "
69 | f"network-manager-applet nm-connection-editor xfce4-pulseaudio-plugin pavucontrol pipewire "
70 | f"gnome-software firefox wireplumber")
71 | chroot("systemctl enable lightdm.service")
72 | case "lxqt":
73 | print_status("Installing LXQt")
74 | chroot(f"{pacman_command} lxqt breeze-icons xorg xorg-server sddm firefox network-manager-applet "
75 | f"nm-connection-editor discover packagekit-qt5")
76 | chroot("systemctl enable sddm.service")
77 | case "deepin":
78 | print_status("Installing deepin")
79 | chroot(f"{pacman_command} deepin deepin-kwin deepin-extra xorg xorg-server lightdm kde-applications firefox"
80 | f" discover packagekit-qt5")
81 | # enable deepin specific login style
82 | with open("/mnt/depthboot/etc/lightdm/lightdm.conf", "a") as conf:
83 | conf.write("greeter-session=lightdm-deepin-greeter")
84 | chroot("systemctl enable lightdm.service")
85 | case "budgie":
86 | print_status("Installing Budgie")
87 | chroot(f"{pacman_command} lightdm lightdm-gtk-greeter budgie-desktop budgie-desktop-view budgie-screensaver"
88 | f" budgie-control-center xorg xorg-server network-manager-applet gnome-terminal firefox "
89 | f"gnome-software nemo")
90 | chroot("systemctl enable lightdm.service")
91 | # remove broken gnome xsessions
92 | chroot("rm /usr/share/xsessions/gnome.desktop")
93 | chroot("rm /usr/share/xsessions/gnome-xorg.desktop")
94 | case "cinnamon":
95 | print_status("Installing Cinnamon")
96 | chroot(f"{pacman_command} cinnamon cinnamon-translations lightdm lightdm-gtk-greeter xed xreader "
97 | f"gnome-terminal system-config-printer gnome-keyring blueberry")
98 | chroot("systemctl enable lightdm.service")
99 | chroot("systemctl enable NetworkManager.service")
100 | case "cli":
101 | print_status("Skipping desktop environment install")
102 | case _:
103 | print_error(f"Invalid desktop environment: {de_name}. Please create an issue")
104 | exit(1)
105 |
106 | if de_name != "cli":
107 | print_status("Installing auto-rotate service, keyd")
108 | chroot(f"{pacman_command} iio-sensor-proxy keyd")
109 |
110 | print_status("Desktop environment setup complete")
111 |
112 | # enable networkmanager systemd service
113 | chroot("systemctl enable NetworkManager.service")
114 | # Enable bluetooth systemd service
115 | chroot("systemctl enable bluetooth")
116 | # Add zram config
117 | cpfile("configs/zram/zram-generator.conf", "/mnt/depthboot/etc/systemd/zram-generator.conf")
118 |
119 | # Configure sudo
120 | # for some reason, the sudoers file sometimes gets reset to default
121 | # -> create file in /etc/sudoers.d instead to preserve changes
122 | with open("/mnt/depthboot/etc/sudoers.d/wheel_conf", "w") as conf:
123 | conf.write("%wheel ALL=(ALL:ALL) ALL") # enable wheel group to use sudo
124 |
125 | print_status("Restoring pacman config")
126 | with open("/mnt/depthboot/etc/pacman.conf", "r") as conf:
127 | temp_pacman = conf.readlines()
128 | # comment out CheckSpace
129 | temp_pacman[34] = temp_pacman[34][1:]
130 | with open("/mnt/depthboot/etc/pacman.conf", "w") as conf:
131 | conf.writelines(temp_pacman)
132 |
133 | # Kill the gpg-agent processes, as they prevent the image from being unmounted later
134 | gpg_pids = []
135 | for line in bash("ps aux").split("\n"):
136 | if "gpg-agent --homedir /etc/pacman.d/gnupg --use-standard-socket --daemon" in line:
137 | # Find the pids of the correct gpg-agent processes
138 | temp_string = line[line.find(" "):].strip()
139 | gpg_pids.append(temp_string[:temp_string.find(" ")])
140 |
141 | for pid in gpg_pids:
142 | print(f"Killing gpg-agent proces with pid: {pid}")
143 | bash(f"kill {pid}")
144 |
145 | print_status("Arch setup complete")
146 |
--------------------------------------------------------------------------------
/distro/debian.py:
--------------------------------------------------------------------------------
1 | from functions import *
2 |
3 |
4 | def config(de_name: str, distro_version: str, verbose: bool, kernel_version: str) -> None:
5 | set_verbose(verbose)
6 | print_status("Configuring Debian")
7 |
8 | # Copy over sources.list (the bootstrap one doesn't have all the stock debian repos)
9 | cpfile("configs/debian-sources.list", "/mnt/depthboot/etc/apt/sources.list")
10 |
11 | print_status("Installing eupnea repo package")
12 | urlretrieve(f"https://github.com/eupnea-project/deb-repo/releases/latest/download/eupnea-{distro_version}-"
13 | f"keyring.deb", filename="/mnt/depthboot/tmp/keyring.deb")
14 | chroot("apt-get install -y /tmp/keyring.deb")
15 | # remove keyring package
16 | rmfile("/mnt/depthboot/tmp/keyring.deb")
17 |
18 | # update apt
19 | chroot("apt-get update -y")
20 | chroot("apt-get upgrade -y")
21 | # Install general dependencies + eupnea packages
22 | print_status("Installing dependencies")
23 | chroot("apt-get install -y network-manager sudo firmware-linux-free firmware-linux-nonfree "
24 | "firmware-iwlwifi iw")
25 | chroot("apt-get update -y")
26 | chroot("apt-get install -y eupnea-utils eupnea-system")
27 |
28 | # Install kernel
29 | chroot(f"apt-get install -y eupnea-{kernel_version}-kernel")
30 |
31 | # Install zram
32 | chroot("apt-get install -y systemd-zram-generator")
33 | # Add zram config
34 | cpfile("configs/zram/zram-generator.conf", "/mnt/depthboot/etc/systemd/zram-generator.conf")
35 |
36 | print_status("Downloading and installing de, might take a while")
37 | # DEBIAN_FRONTEND=noninteractive skips locale setup questions
38 | # package names taken from https://www.debian.org/doc/manuals/debian-reference/ch07.en.html
39 | match de_name:
40 | case "gnome":
41 | print_status("Installing GNOME")
42 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y task-gnome-desktop")
43 | case "kde":
44 | print_status("Installing KDE")
45 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y task-kde-desktop")
46 | case "xfce":
47 | print_status("Installing Xfce")
48 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y task-xfce-desktop xfce4-pulseaudio-plugin "
49 | "gnome-software epiphany-browser")
50 | case "lxqt":
51 | print_status("Installing LXQt")
52 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y task-lxqt-desktop plasma-discover")
53 | case "deepin":
54 | print_error("Deepin is not available for Debian")
55 | exit(1)
56 | case "budgie":
57 | print_status("Installing Budgie")
58 | chroot("DEBIAN_FRONTEND=noninteractive apt-get -y --install-suggests install budgie-desktop lightdm "
59 | "lightdm-gtk-greeter epiphany-browser gnome-software")
60 | chroot("systemctl enable lightdm.service")
61 | case "cinnamon":
62 | print_status("Installing Cinnamon")
63 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y task-cinnamon-desktop")
64 | case "cli":
65 | print_status("Skipping desktop environment install")
66 | case _:
67 | print_error("Invalid desktop environment! Please create an issue")
68 | exit(1)
69 |
70 | if de_name != "cli":
71 | # Set system to boot to gui
72 | chroot("systemctl set-default graphical.target")
73 | # Replace input-synaptics with newer input-libinput, for better touchpad support
74 | print_status("Upgrading touchpad drivers")
75 | chroot("apt-get remove -y xserver-xorg-input-synaptics")
76 | chroot("apt-get install -y xserver-xorg-input-libinput")
77 | print_status("Installing keyd")
78 | chroot("apt-get install -y keyd")
79 |
80 | # GDM3 auto installs gnome-minimal. Remove it if user didn't choose gnome
81 | if de_name != "gnome":
82 | # rmfile("/mnt/depthboot/usr/share/xsessions/debian.desktop")
83 | chroot("apt-get remove -y gnome-shell")
84 | chroot("apt-get autoremove -y")
85 |
86 | # Fix gdm3, https://askubuntu.com/questions/1239503/ubuntu-20-04-and-20-10-etc-securetty-no-such-file-or-directory
87 | with contextlib.suppress(FileNotFoundError):
88 | cpfile("/mnt/depthboot/usr/share/doc/util-linux/examples/securetty", "/mnt/depthboot/etc/securetty")
89 | print_status("Desktop environment setup complete")
90 |
91 | print_status("Debian setup complete")
92 |
--------------------------------------------------------------------------------
/distro/fedora.py:
--------------------------------------------------------------------------------
1 | from functions import *
2 |
3 |
4 | def config(de_name: str, distro_version: str, verbose: bool, kernel_version: str) -> None:
5 | set_verbose(verbose)
6 | print_status("Configuring Fedora")
7 |
8 | # Tweak dnf config to enable multithreaded downloads
9 | with open("/mnt/depthboot/etc/dnf/dnf.conf", "r") as f:
10 | og_dnf_conf = f.read()
11 | new_dnf_conf = og_dnf_conf.replace("installonly_limit=3", "installonly_limit=0")
12 | new_dnf_conf += "\nfastestmirror=True\nmax_parallel_downloads=10\n"
13 | with open("/mnt/depthboot/etc/dnf/dnf.conf", "w") as f:
14 | f.write(new_dnf_conf)
15 |
16 | print("Installing dependencies")
17 | chroot(f"dnf install -y --releasever={distro_version} fedora-release") # update repos list
18 | # Add eupnea repo
19 | chroot("dnf config-manager --add-repo https://eupnea-project.github.io/rpm-repo/eupnea.repo")
20 | chroot("dnf update --refresh -y") # update repos
21 | # Install eupnea packages
22 | chroot("dnf install -y eupnea-system eupnea-utils")
23 | # Install kernel
24 | chroot(f"dnf install -y eupnea-{kernel_version}-kernel")
25 | # Install core packages
26 | chroot("dnf group install -y 'Core'")
27 | # Install firmware packages
28 | chroot("dnf group install -y 'Hardware Support'")
29 | chroot("dnf group install -y 'Common NetworkManager Submodules'")
30 | chroot("dnf install -y linux-firmware")
31 |
32 | print_status("Downloading and installing DE, might take a while")
33 | match de_name:
34 | case "gnome":
35 | print_status("Installing GNOME")
36 | chroot("dnf group install -y 'Fedora Workstation'") # Fedora has gnome by default in a workstation install
37 | chroot("dnf install -y firefox")
38 | case "kde":
39 | print_status("Installing KDE")
40 | chroot("dnf group install -y 'KDE Plasma Workspaces'")
41 | chroot("dnf install -y firefox")
42 | case "xfce":
43 | print_status("Installing Xfce")
44 | chroot("dnf group install -y 'Xfce Desktop'")
45 | chroot("dnf install -y firefox gnome-software xfce4-pulseaudio-plugin")
46 | case "lxqt":
47 | print_status("Installing LXQt")
48 | chroot("dnf group install -y 'LXQt Desktop'")
49 | chroot("dnf install -y plasma-discover")
50 | case "deepin":
51 | print_status("Installing deepin")
52 | chroot("dnf group install -y 'Deepin Desktop'")
53 | chroot("dnf install -y plasma-discover")
54 | case "budgie":
55 | print_status("Installing Budgie")
56 | chroot("dnf install -y budgie-desktop lightdm lightdm-gtk xorg-x11-server-Xorg gnome-terminal firefox "
57 | "gnome-software nemo")
58 | case "cinnamon":
59 | print_status("Installing Cinnamon")
60 | chroot("dnf group install -y 'Cinnamon Desktop'")
61 | case "cli":
62 | print_status("Skipping desktop environment install")
63 | # install network tui
64 | chroot("dnf install -y NetworkManager-tui")
65 | case _:
66 | print_error("Invalid desktop environment! Please create an issue")
67 | exit(1)
68 |
69 | if de_name != "cli":
70 | # Set system to boot to gui
71 | chroot("systemctl set-default graphical.target")
72 | # install keyd
73 | chroot("dnf install -y keyd")
74 | print_status("Desktop environment setup complete")
75 |
76 | # Add zram config
77 | cpfile("configs/zram/zram-generator.conf", "/mnt/depthboot/etc/systemd/zram-generator.conf")
78 |
79 | # Restore dnf config
80 | with open("/mnt/depthboot/etc/dnf/dnf.conf", "w") as f:
81 | f.write(og_dnf_conf)
82 |
83 | print_status("Fedora setup complete")
84 |
--------------------------------------------------------------------------------
/distro/pop_os.py:
--------------------------------------------------------------------------------
1 | from functions import *
2 |
3 |
4 | def config(de_name: str, distro_version: str, verbose: bool, kernel_version: str) -> None:
5 | set_verbose(verbose)
6 | print_status("Configuring Pop!_OS")
7 |
8 | print_status("Removing casper debs")
9 | # List of packages to remove was taken from /cdrom/casper/filesystem.manifest-remove from the iso
10 | chroot("apt-get purge -y btrfs-progs casper cifs-utils distinst distinst-v2 dmraid expect f2fs-tools fatresize "
11 | "gettext gparted gparted-common grub-common grub2-common kpartx kpartx-boot libdistinst libdmraid1.0.0.rc16"
12 | " libinih1 libnss-mymachines localechooser-data os-prober pop-installer pop-installer-casper pop-shop-casper"
13 | " squashfs-tools systemd-container tcl-expect user-setup xfsprogs kernelstub efibootmgr")
14 |
15 | print_status("Installing eupnea repo package")
16 | # Install eupnea repo package
17 | urlretrieve(f"https://github.com/eupnea-project/deb-repo/releases/latest/download/eupnea-jammy-keyring.deb",
18 | filename="/mnt/depthboot/tmp/keyring.deb")
19 | chroot("apt-get install -y /tmp/keyring.deb")
20 | # remove keyring package
21 | rmfile("/mnt/depthboot/tmp/keyring.deb")
22 |
23 | # update apt
24 | print_status("Updating and upgrading all packages")
25 | chroot("apt-get update -y")
26 | chroot("apt-get upgrade -y")
27 | print_status("Installing eupnea packages")
28 | # Install eupnea packages
29 | chroot("apt-get install -y eupnea-utils eupnea-system keyd")
30 |
31 | # Install kernel
32 | chroot(f"apt-get install -y eupnea-{kernel_version}-kernel")
33 |
34 | # Replace input-synaptics with newer input-libinput, for better touchpad support
35 | print_status("Upgrading touchpad drivers")
36 | chroot("apt-get remove -y xserver-xorg-input-synaptics")
37 | chroot("apt-get install -y xserver-xorg-input-libinput")
38 |
39 | # Enable wayland
40 | print_status("Enabling Wayland")
41 | with open("/mnt/depthboot/etc/gdm3/custom.conf", "r") as file:
42 | gdm_config = file.read()
43 | with open("/mnt/depthboot/etc/gdm3/custom.conf", "w") as file:
44 | file.write(gdm_config.replace("WaylandEnable=false", "#WaylandEnable=false"))
45 | # TODO: Set wayland as default
46 |
47 | print_status("Pop!_OS setup complete")
48 |
--------------------------------------------------------------------------------
/distro/ubuntu.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | from functions import *
4 |
5 |
6 | def config(de_name: str, distro_version: str, verbose: bool, kernel_version: str) -> None:
7 | set_verbose(verbose)
8 | print_status("Configuring Ubuntu")
9 |
10 | ubuntu_versions_codenames = {
11 | "18.04": "bionic",
12 | "20.04": "focal",
13 | "21.04": "hirsute",
14 | "22.04": "jammy",
15 | "22.10": "kinetic",
16 | "23.04": "lunar",
17 | "23.10": "mantic"
18 | }
19 | # add missing apt sources
20 | with open("/mnt/depthboot/etc/apt/sources.list", "a") as file:
21 | file.write(f"\ndeb http://archive.ubuntu.com/ubuntu {ubuntu_versions_codenames[distro_version]}-backports main "
22 | "restricted universe multiverse\n")
23 | file.write(f"\ndeb http://security.ubuntu.com/ubuntu {ubuntu_versions_codenames[distro_version]}-security main"
24 | f" restricted universe multiverse\n")
25 | file.write(f"\ndeb http://archive.ubuntu.com/ubuntu {ubuntu_versions_codenames[distro_version]}-updates main "
26 | f"restricted universe multiverse\n")
27 |
28 | print_status("Installing eupnea repo package")
29 | # Install eupnea repo package
30 | urlretrieve(f"https://github.com/eupnea-project/deb-repo/releases/latest/download/eupnea-"
31 | f"{ubuntu_versions_codenames[distro_version]}-keyring.deb", filename="/mnt/depthboot/tmp/keyring.deb")
32 | chroot("apt-get install -y /tmp/keyring.deb")
33 | # remove keyring package
34 | rmfile("/mnt/depthboot/tmp/keyring.deb")
35 |
36 | # update apt
37 | chroot("apt-get update -y")
38 | chroot("apt-get upgrade -y")
39 | print_status("Installing packages")
40 | # Install general dependencies + eupnea packages
41 | chroot("apt-get install -y linux-firmware network-manager software-properties-common nano eupnea-utils "
42 | "eupnea-system")
43 |
44 | # Install kernel
45 | chroot(f"apt-get install -y eupnea-{kernel_version}-kernel")
46 |
47 | print_status("Installing zram, ignore dpkg errors")
48 | # Install zram
49 | if distro_version == "22.04":
50 | # The jammy deb postinstall of this zram packages tries to modload zram which is not possible in a chroot
51 | # -> ignore errors on jammy
52 | with contextlib.suppress(subprocess.CalledProcessError):
53 | chroot("apt-get install -y systemd-zram-generator")
54 | # Edit the postinstall script to force success
55 | with open("/mnt/depthboot/var/lib/dpkg/info/systemd-zram-generator.postinst", "r") as file:
56 | config = file.read()
57 | with open("/mnt/depthboot/var/lib/dpkg/info/systemd-zram-generator.postinst", "w") as file:
58 | file.write("#!/bin/sh\nexit 0\n")
59 | # Rerun dpkg configuration for package to be recognized as installed
60 | # for some reason on some systems dpkg says that the package is already installed -> ignore it
61 | with contextlib.suppress(subprocess.CalledProcessError):
62 | chroot("dpkg --configure systemd-zram-generator")
63 | # Restore original postinstall script
64 | with open("/mnt/depthboot/var/lib/dpkg/info/systemd-zram-generator.postinst", "w") as file:
65 | file.write(config)
66 | else:
67 | # if not on jammy, do not ignore errors from this command
68 | chroot("apt-get install -y systemd-zram-generator")
69 |
70 | print_status("Downloading and installing de, might take a while")
71 | match de_name:
72 | case "gnome":
73 | print_status("Installing GNOME")
74 | chroot("apt-get install -y ubuntu-desktop gnome-software epiphany-browser wireplumber")
75 | case "kde":
76 | print_status("Installing KDE")
77 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y kde-standard plasma-workspace-wayland "
78 | "sddm-theme-breeze wireplumber")
79 | case "xfce":
80 | print_status("Installing Xfce")
81 | # install xfce without heavy unnecessary packages
82 | chroot("apt-get install -y xubuntu-desktop gimp- gnome-font-viewer- gnome-mines- gnome-sudoku- gucharmap-"
83 | " hexchat- libreoffice-*- mate-calc- pastebinit- synaptic- thunderbird- transmission-gtk-")
84 | chroot("apt-get install -y nano gnome-software epiphany-browser")
85 | case "lxqt":
86 | print_status("Installing LXQt")
87 | chroot("apt-get install -y lubuntu-desktop discover konqueror")
88 | case "deepin":
89 | print_status("Installing deepin")
90 | chroot("add-apt-repository -y ppa:ubuntudde-dev/stable")
91 | chroot("apt-get update -y")
92 | with contextlib.suppress(subprocess.CalledProcessError):
93 | chroot("apt-get install -y ubuntudde-dde")
94 | # remove dpkg deepin-anything files to avoid dpkg errors
95 | # These are later reinstated by the postinstall script
96 | for file in os.listdir("/mnt/depthboot/var/lib/dpkg/info/"):
97 | if file.startswith("deepin-anything-"):
98 | rmfile(f"/mnt/depthboot/var/lib/dpkg/info/{file}")
99 | chroot("apt-get install -y discover konqueror")
100 | case "budgie":
101 | print_status("Installing Budgie")
102 | # do not install tex-common, it breaks the installation
103 | chroot("DEBIAN_FRONTEND=noninteractive apt-get install -y lightdm lightdm-gtk-greeter ubuntu-budgie-desktop"
104 | " tex-common-")
105 | case "cinnamon":
106 | print_status("Installing Cinnamon")
107 | chroot("apt-get install -y cinnamon-desktop-environment")
108 | case "cli":
109 | print_status("Skipping desktop environment install")
110 | case _:
111 | print_error("Invalid desktop environment! Please create an issue")
112 | exit(1)
113 |
114 | if de_name != "cli":
115 | # Replace input-synaptics with newer input-libinput, for better touchpad support
116 | print_status("Upgrading touchpad drivers")
117 | chroot("apt-get remove -y xserver-xorg-input-synaptics")
118 | chroot("apt-get install -y xserver-xorg-input-libinput")
119 | print_status("Installing keyd")
120 | chroot("apt-get install -y keyd")
121 |
122 | # Install libasound2 backport on jammy
123 | if distro_version == "22.04":
124 | chroot("apt-get install -y libasound2-eupnea")
125 |
126 | # GDM3 auto installs gnome-minimal. Gotta remove it if user didn't choose gnome
127 | if de_name != "gnome":
128 | rmfile("/mnt/depthboot/usr/share/xsessions/ubuntu.desktop")
129 | chroot("apt-get remove -y gnome-shell")
130 | chroot("apt-get autoremove -y")
131 |
132 | # Fix gdm3, https://askubuntu.com/questions/1239503/ubuntu-20-04-and-20-10-etc-securetty-no-such-file-or-directory
133 | with contextlib.suppress(FileNotFoundError):
134 | cpfile("/mnt/depthboot/usr/share/doc/util-linux/examples/securetty", "/mnt/depthboot/etc/securetty")
135 | print_status("Desktop environment setup complete")
136 |
137 | print_status("Ubuntu setup complete")
138 |
--------------------------------------------------------------------------------
/functions.py:
--------------------------------------------------------------------------------
1 | import contextlib
2 | import subprocess
3 | import sys
4 | from pathlib import Path
5 | from threading import Thread
6 | from time import sleep
7 | from urllib.request import urlopen, urlretrieve
8 |
9 |
10 | #######################################################################################
11 | # PATHLIB FUNCTIONS #
12 | #######################################################################################
13 | # unlink all files in a directory and remove the directory
14 | def rmdir(rm_dir: str, keep_dir: bool = True) -> None:
15 | def unlink_files(path_to_rm: Path) -> None:
16 | try:
17 | for file in path_to_rm.iterdir():
18 | if file.is_file():
19 | file.unlink()
20 | else:
21 | unlink_files(path_to_rm)
22 | except FileNotFoundError:
23 | print(f"Couldn't remove non existent directory: {path_to_rm}, ignoring")
24 |
25 | # convert string to Path object
26 | rm_dir_as_path = Path(rm_dir)
27 | try:
28 | unlink_files(rm_dir_as_path)
29 | except RecursionError: # python doesn't work for folders with a lot of subfolders
30 | print(f"Failed to remove {rm_dir} with python, using bash")
31 | bash(f"rm -rf {rm_dir_as_path.absolute().as_posix()}/*")
32 | # Remove emtpy directory
33 | if not keep_dir:
34 | try:
35 | rm_dir_as_path.rmdir()
36 | except FileNotFoundError: # Directory doesn't exist, because bash was used
37 | return
38 |
39 |
40 | # remove a single file
41 | def rmfile(file: str, force: bool = False) -> None:
42 | if force: # for symbolic links
43 | Path(file).unlink(missing_ok=True)
44 | file_as_path = Path(file)
45 | with contextlib.suppress(FileNotFoundError):
46 | file_as_path.unlink()
47 |
48 |
49 | # make directory
50 | def mkdir(mk_dir: str, create_parents: bool = False) -> None:
51 | mk_dir_as_path = Path(mk_dir)
52 | if not mk_dir_as_path.exists():
53 | mk_dir_as_path.mkdir(parents=create_parents)
54 |
55 |
56 | def path_exists(path_str: str) -> bool:
57 | return Path(path_str).exists()
58 |
59 |
60 | def get_full_path(path_str: str) -> str:
61 | return Path(path_str).absolute().as_posix()
62 |
63 |
64 | # recursively copy files from a dir into another dir
65 | def cpdir(src_as_str: str, dst_as_string: str) -> None: # dst_dir must be a full path, including the new dir name
66 | def copy_files(src: Path, dst: Path) -> None:
67 | # create dst dir if it doesn't exist
68 | if verbose:
69 | print(f"Copying {src} to {dst}")
70 | mkdir(dst.absolute().as_posix(), create_parents=True)
71 | for src_file in src.iterdir():
72 | if src_file.is_file():
73 | dst_file = dst.joinpath(src_file.stem + src_file.suffix)
74 | dst_file.write_bytes(src_file.read_bytes())
75 | elif src_file.is_dir():
76 | if src_file.exists():
77 | new_dst = dst.joinpath(src_file.stem + src_file.suffix)
78 | copy_files(src_file, new_dst)
79 | else:
80 | raise FileNotFoundError(f"No such file or directory: {src_file.absolute().as_posix()}")
81 |
82 | src_as_path = Path(src_as_str)
83 | dst_as_path = Path(dst_as_string)
84 | if src_as_path.exists():
85 | if not dst_as_path.exists():
86 | mkdir(dst_as_string)
87 | # TODO: Fix python copy dir
88 | '''
89 | try:
90 | copy_files(src_as_path, dst_as_path)
91 | except RecursionError:
92 | print("\033[93m" + f"Failed to copy {root_src} to {root_dst}, using bash" + "\033[0m")
93 | bash(f"cp -rp {src_as_path.absolute().as_posix()} {dst_as_path.absolute().as_posix()}")
94 | '''
95 | bash(f"cp -rp {src_as_path.absolute().as_posix()}/* {dst_as_path.absolute().as_posix()}")
96 | else:
97 | raise FileNotFoundError(f"No such directory: {src_as_path.absolute().as_posix()}")
98 |
99 |
100 | def cpfile(src_as_str: str, dst_as_str: str) -> None: # "/etc/resolv.conf", "/var/some_config/resolv.conf"
101 | src_as_path = Path(src_as_str)
102 | dst_as_path = Path(dst_as_str)
103 | if verbose:
104 | print(f"Copying {src_as_path.absolute().as_posix()} to {dst_as_path.absolute().as_posix()}")
105 | if src_as_path.exists():
106 | dst_as_path.write_bytes(src_as_path.read_bytes())
107 | else:
108 | raise FileNotFoundError(f"No such file: {src_as_path.absolute().as_posix()}")
109 |
110 |
111 | #######################################################################################
112 | # BASH FUNCTIONS #
113 | #######################################################################################
114 |
115 | # return the output of a command
116 | def bash(command: str) -> str:
117 | output = subprocess.check_output(command, shell=True, text=True).strip()
118 | if verbose:
119 | print(output, flush=True)
120 | return output
121 |
122 |
123 | def chroot(command: str) -> str:
124 | return bash(f'chroot /mnt/depthboot /bin/bash -c "{command}"')
125 |
126 |
127 | #######################################################################################
128 | # MISC STUFF #
129 | #######################################################################################
130 |
131 | def set_verbose(new_state: bool) -> None:
132 | global verbose
133 | verbose = new_state
134 |
135 |
136 | def prevent_idle() -> None:
137 | Thread(target=__prevent_idle, daemon=True).start()
138 |
139 |
140 | def __prevent_idle():
141 | bash('systemd-inhibit /bin/bash -c "sleep 14400" --what="idle"') # sleep indefinitely, thereby preventing idle
142 | print_error("Been copying for 4 HOURS?!?!? Please create an issue")
143 |
144 |
145 | #######################################################################################
146 | # PACKAGE MANAGER PROGRESS MONITOR FUNCTIONS #
147 | #######################################################################################
148 | # TO AVOID ISSUES: Sync all repos before calling package manager functions
149 | # The functions below, will start a thread to monitor the progress of their respective package managers
150 |
151 | def track_apt(path_to_log: str) -> None:
152 | Thread(target=_track_apt, args=(path_to_log,), daemon=True).start()
153 |
154 |
155 | def track_dnf(path_to_log) -> None:
156 | Thread(target=_track_dnf, args=(path_to_log,), daemon=True).start()
157 |
158 |
159 | def track_pacman(path_to_log) -> None:
160 | # The actual start of this function is at the bottom
161 | def _track_pacman() -> None:
162 | # As funny as it may sound in python, this function is optimized for performance, due to the huge amount of
163 | # disk I/O Therefore some functions could be shorter, but that might increase the already relatively huge load.
164 | # wait for install to start
165 | while not path_exists(path_to_log):
166 | sleep(0.1)
167 | # wait for total package amount to appear in log
168 | stop = False
169 | while not stop:
170 | sleep(1)
171 | with open(path_to_log, "r") as file:
172 | log = file.readlines()
173 | for line in log:
174 | if "Old Version New Version Net Change Download Size" in line:
175 | total_packages = int(line.strip().split(" ")[1][1:-1])
176 | stop = True
177 | break
178 |
179 | # wait and find line where packages start to download
180 | # Pacman might be resolving dependencies, so we need to wait for that to finish
181 | stop = False
182 | while not stop:
183 | sleep(1)
184 | with open(path_to_log, "r") as file:
185 | log = file.readlines()
186 | for line in log:
187 | if ":: Retrieving packages..." in line:
188 | download_start_index = log.index(line) + 1
189 | stop = True
190 | break
191 |
192 | # Print download progress
193 | stop = False
194 | downloaded_functions = []
195 | while not stop:
196 | sleep(1)
197 | with open(path_to_log, "r") as file:
198 | log = file.readlines()
199 | for line in log[download_start_index:]: # check lines after the start index to increase performance
200 | if ":: Processing package changes..." in line: # pacman is preparing to install packages
201 | install_start_index = log.index(line) + 1
202 | stop = True
203 | break
204 | package = line.strip()[:-15]
205 | if package not in downloaded_functions:
206 | print(f"Downloading {package}, ({len(downloaded_functions)}/{total_packages})", end="\r",
207 | flush=True)
208 | downloaded_functions.append(package)
209 |
210 | # Print install progress
211 | stop = False
212 | installed_packages = []
213 | while not stop:
214 | sleep(1)
215 | with open(path_to_log, "r") as file:
216 | log = file.readlines()
217 | for line in log[
218 | install_start_index:]: # only check lines after the install start to increase performance
219 | if ":: Running post-transaction hooks..." in line: # pacman is preparing to run post install hooks
220 | post_install_start_index = log.index(line) + 1
221 | stop = True
222 | break
223 | if "installing " in line:
224 | package = line.strip()[11:-3]
225 | if package not in installed_packages:
226 | print(f"Installing package {package}, ({len(installed_packages)}/{total_packages})",
227 | end="\r",
228 | flush=True)
229 | installed_packages.append(package)
230 |
231 | # Monitor postinstall hooks
232 | # Don't print the full output, as it might include "scary"-ish messages
233 | stop = False
234 | while not stop:
235 | sleep(1)
236 | with open(path_to_log, "r") as file:
237 | log = file.readlines()
238 | for line in log[post_install_start_index:]:
239 | # pacman has no final success message, so we have to manually check if the install is finished
240 | if not line.startswith("("): # if the line doesn't start with a number, it's not relevant for us
241 | continue
242 | temp_line = line.strip().split(" ")[0]
243 | # check if this is the last line by comparing the numbers inside the brackets
244 | if temp_line[1:-1].split("/")[0] == temp_line[1:-1].split("/")[1]:
245 | print("Installation finished", flush=True)
246 | stop = True
247 | break
248 | print(f"Running postinstall hooks: {temp_line}", end="\r", flush=True)
249 | installed_packages.append(package)
250 |
251 | Thread(target=_track_pacman, daemon=True).start()
252 |
253 |
254 | # Track progress of apt/apt-get
255 | def _track_apt(path_to_log) -> None:
256 | pass
257 |
258 |
259 | # Track progress of dnf
260 | def _track_dnf(path_to_log) -> None:
261 | pass
262 |
263 |
264 | #######################################################################################
265 | # FILE PROGRESS MONITOR FUNCTIONS #
266 | #######################################################################################
267 |
268 | def extract_file(file: str, dest: str) -> None:
269 | """
270 | Extract a compressed file using tar and use pv to show progress if pv is installed.
271 |
272 | :param file: A string representing the full path to the compressed file to be extracted.
273 | :param dest: A string representing the full destination directory where the extracted files will be extracted to.
274 | :return: None
275 | """
276 | if no_extract_progress: # for non-interactive shells only
277 | if file.endswith(".gz"):
278 | # --warning=no-unknown-keyword is to supress a warning about unknown headers in the arch rootfs
279 | bash(f"tar xfpz {file} --warning=no-unknown-keyword -C {dest}")
280 | elif file.endswith(".xz"):
281 | bash(f"tar xfpJ {file} -C {dest}")
282 | return
283 |
284 | if file.endswith(".gz"):
285 | # --warning=no-unknown-keyword is to supress a warning about unknown headers in the arch rootfs
286 | bash(f"pv {file} | tar xfpz - --warning=no-unknown-keyword -C {dest}")
287 | elif file.endswith(".xz"):
288 | bash(f"pv {file} | tar xfpJ - -C {dest}")
289 |
290 |
291 | def download_file(url: str, path: str) -> None:
292 | # start monitor in a separate thread
293 | if no_download_progress: # for non-interactive shells only
294 | # start download
295 | urlretrieve(url=url, filename=path)
296 | return
297 |
298 | # get total file size from server
299 | total_file_size = int(urlopen(url).headers["Content-Length"])
300 | Thread(target=_print_download_progress, args=(Path(path), total_file_size,), daemon=True).start()
301 |
302 | # start download
303 | urlretrieve(url=url, filename=path)
304 |
305 | # stop monitor
306 | open(".stop_download_progress", "a").close()
307 | print("\n", end="")
308 |
309 |
310 | def _print_download_progress(file_path: Path, total_size) -> None:
311 | while True:
312 | if path_exists(".stop_download_progress"):
313 | rmfile(".stop_download_progress")
314 | return
315 | try:
316 | print("\rDownloading: " + "%.0f" % int(file_path.stat().st_size / 1048576) + "mb / "
317 | + "%.0f" % (total_size / 1048576) + "mb", end="", flush=True)
318 | except FileNotFoundError:
319 | sleep(0.5) # in case download hasn't started yet
320 |
321 |
322 | #######################################################################################
323 | # PRINT FUNCTIONS #
324 | #######################################################################################
325 |
326 | # tree implementation in python
327 | # Credit: https://stackoverflow.com/a/59109706
328 | def create_tree(dir_str: str) -> str:
329 | # TODO: sort alphabetically
330 | def tree(dir_path: Path, prefix: str = ''):
331 | # prefix components:
332 | space = ' '
333 | branch = '│ '
334 | # pointers:
335 | tee = '├── '
336 | last = '└── '
337 |
338 | dir_path.iterdir()
339 | contents = list(dir_path.iterdir())
340 | # contents each get pointers that are ├── with a final └── :
341 | pointers = [tee] * (len(contents) - 1) + [last]
342 | for pointer, path in zip(pointers, contents):
343 | yield prefix + pointer + path.name
344 | if path.is_dir(): # extend the prefix and recurse:
345 | extension = branch if pointer == tee else space
346 | # i.e. space because last, └── , above so no more |
347 | yield from tree(path, prefix=prefix + extension)
348 |
349 | final_tree = dir_str + "\n"
350 | for line in tree(Path(dir_str)):
351 | final_tree += line + "\n"
352 | return final_tree
353 |
354 |
355 | def print_warning(message: str) -> None:
356 | print("\033[93m" + message + "\033[0m", flush=True)
357 |
358 |
359 | def print_error(message: str) -> None:
360 | print("\033[91m" + message + "\033[0m", flush=True)
361 |
362 |
363 | def print_status(message: str) -> None:
364 | print("\033[94m" + message + "\033[0m", flush=True)
365 |
366 |
367 | def print_question(message: str) -> None:
368 | print("\033[92m" + message + "\033[0m", flush=True)
369 |
370 |
371 | def print_header(message: str) -> None:
372 | print("\033[95m" + message + "\033[0m", flush=True)
373 |
374 |
375 | verbose = False
376 | # on import check if pv is installed and set global variable
377 | try:
378 | bash("which pv > /dev/null 2>&1") # suppress all output to avoid scaring the user (pv is not a hard dependency)
379 | no_extract_progress = False
380 | except subprocess.CalledProcessError:
381 | no_extract_progress = True
382 | no_download_progress = not sys.stdout.isatty() # disable download progress if terminal is not interactive
383 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # This script will later become the gui. For now, it's a simple wrapper for the build script.
3 |
4 | import argparse
5 | import atexit
6 | import os
7 |
8 | from functions import *
9 |
10 | global user_cancelled
11 | user_cancelled = False
12 |
13 |
14 | # parse arguments from the cli. Only for testing/advanced use. All other parameters are handled by cli_input.py
15 | def process_args():
16 | parser = argparse.ArgumentParser()
17 | # action="store_true" makes the arg a flag and sets it to True if the argument is passed, without needing a value
18 | parser.add_argument('-p', dest="local_path",
19 | help="Use this option with the full path to the directory with files to be used by the script."
20 | " If a file is not found the script will attempt to download it.")
21 | parser.add_argument('--device', dest="device_override",
22 | help="Specify device to direct write. Skips the device selection question.")
23 | parser.add_argument("--show-device-selection", dest="device_selection", action="store_true",
24 | help="Show device selection menu instead of automatically building image")
25 | parser.add_argument("-v", "--verbose", dest="verbose", help="Print more output", action="store_true")
26 | parser.add_argument("--no-shrink", dest="no_shrink", help="Do not shrink image", action="store_true")
27 | parser.add_argument("--no-deps-check", dest="no_deps_check", help="Do not check if dependencies are installed",
28 | action="store_true")
29 | parser.add_argument("--verbose-kernel", dest="verbose_kernel", action="store_true",
30 | help="Set loglevel=15 in cmdline for visible kernel logs on boot")
31 | parser.add_argument("--skip-size-check", dest="skip_size_check", action="store_true",
32 | help="Do not check available disk space")
33 | parser.add_argument("-i", dest="image_size", type=int, nargs=1, default=[10],
34 | help="Override image size(default: 10GB)")
35 | parser.add_argument("--dev", dest="dev_build", action="store_true", help="Use latest dev build. May be unstable.")
36 | parser.add_argument("--skip-commit-check", dest="skip_commit_check", action="store_true",
37 | help="Do not check if local commit hash matches remote commit hash")
38 | parser.add_argument("--skip-arch-check", dest="skip_arch_check", action="store_true",
39 | help="Do not check the architecture of the builder system")
40 | return parser.parse_args()
41 |
42 |
43 | class ExitHooks(object):
44 | def __init__(self):
45 | self.exit_code = None
46 |
47 | def hook(self):
48 | self._orig_exit = sys.exit
49 | self._orig_excepthook = sys.excepthook
50 | self._orig_exc_handler = self.exc_handler
51 | sys.exit = self.exit
52 | sys.excepthook = self.exc_handler
53 |
54 | def exit(self, code=0):
55 | self.exit_code = code
56 | self._orig_exit(code)
57 |
58 | def exc_handler(self, exc_type, exc, *args):
59 | if exc_type == KeyboardInterrupt:
60 | global user_cancelled
61 | user_cancelled = True
62 | else:
63 | sys.__excepthook__(exc_type, exc, *args)
64 |
65 |
66 | def exit_handler():
67 | if user_cancelled:
68 | print_error("\nUser cancelled, exiting")
69 | return
70 | if hooks.exit_code not in [0, 1]: # ignore normal exit codes
71 | print_error("Script exited unexpectedly, please open an issue on GitHub/Discord/Revolt")
72 | print_question('Run "./main.py -v" to restart with more verbose output\n'
73 | 'Run "./main.py --help" for more options')
74 |
75 |
76 | if __name__ == "__main__":
77 | # override sys.exit to catch exit codes
78 | hooks = ExitHooks()
79 | hooks.hook()
80 | atexit.register(exit_handler)
81 | # set locale env var to supress locale warnings in package managers
82 | os.environ["LC_ALL"] = "C"
83 |
84 | args = process_args()
85 | if args.dev_build:
86 | print_error("Dev builds are not supported currently")
87 | sys.exit(1)
88 |
89 | # check if running the latest version of the script
90 | print_status("Checking if local script is up to date")
91 | try:
92 | if (not args.skip_commit_check and
93 | bash("git rev-parse HEAD") != bash("git ls-remote origin HEAD").split("\t")[0]):
94 | user_answer = input("\033[92m" + "You are not running the latest version of the script. Update now? (Y/n): "
95 | + "\033[0m").lower()
96 | if user_answer.lower() in ["y", ""]:
97 | print_status("Updating the script...")
98 | bash("git pull")
99 | print_status("Restarting the script...")
100 | # clear terminal, but keep any previous output so the user can scroll up to see it
101 | print("\033[H\033[2J", end="")
102 | os.execl(sys.executable, sys.executable, *sys.argv)
103 | print_error("Please update the script before continuing.")
104 | print_status("If you are a developer, you can skip this check with the '--skip-commit-check' flag")
105 | sys.exit(1)
106 | except subprocess.CalledProcessError:
107 | print_error("Failed to check if script is up to date.")
108 | print_status("If you are a developer, you can skip this by setting the '--skip-commit-check' flag. "
109 | "If you are not a developer, check your internet connection and try again.")
110 | sys.exit(1)
111 |
112 | # Restart script as root
113 | if os.geteuid() != 0:
114 | print_header("The script requires root privileges to mount the image/device and write to it, "
115 | "as well as for installing dependencies on the build system")
116 | print_status("Requesting root privileges...")
117 | sudo_args = ['sudo', sys.executable] + sys.argv + [os.environ]
118 | os.execlpe('sudo', *sudo_args)
119 |
120 | # PATH vars are inherited in chroots -> check if the current path has /usr/sbin, as some systems dont have that var
121 | # but some chroot distros expect them to be set
122 | if not os.environ.get("PATH").__contains__("/usr/sbin"):
123 | os.environ["PATH"] += ":/usr/sbin"
124 |
125 | print_status("Checking if running on x86_64")
126 | if not bash("uname -m") == "x86_64" and not args.skip_arch_check:
127 | print_error("Building is only supported on x86_64 systems at the moment. Please use a translation layer or a "
128 | "virtual machine if you want to build from another architecture")
129 | print_status("If you are a developer, you can skip this by setting the '--skip-arch-check' flag.")
130 | sys.exit(1)
131 |
132 | # check script dependencies are already installed with which
133 | if not args.no_deps_check:
134 | print_status("Checking if script dependencies are installed...")
135 | try:
136 | bash("which pv xz parted cgpt futility")
137 | print_status("Dependencies already installed, skipping")
138 | except subprocess.CalledProcessError:
139 | print_status("Installing dependencies")
140 | with open("/etc/os-release", "r") as os:
141 | distro = os.read()
142 | if distro.lower().__contains__(
143 | "arch"): # might accidentally catch architecture stuff, but needed to catch arch derivatives
144 | bash("pacman -Sy") # sync repos
145 | # Download prepackaged cgpt + vboot from arch-repo releases as its not available in the official repos
146 | # Makepkg is too much of a hassle to use here as it requires a non-root user
147 | urlretrieve("https://github.com/eupnea-project/arch-repo/releases/latest/download/cgpt-vboot"
148 | "-utils.pkg.tar.gz", filename="/tmp/cgpt-vboot-utils.pkg.tar.gz")
149 | # Install downloaded package
150 | bash("pacman --noconfirm -U /tmp/cgpt-vboot-utils.pkg.tar.gz")
151 | # Install other dependencies
152 | bash("pacman --noconfirm -S pv xz parted")
153 | elif distro.lower().__contains__("void"):
154 | bash("xbps-install -y --sync")
155 | bash("xbps-install -y pv xz parted cgpt vboot-utils")
156 | elif distro.lower().__contains__("ubuntu") or distro.lower().__contains__("debian"):
157 | bash("apt-get update -y") # sync repos
158 | bash("apt-get install -y pv xz-utils parted cgpt vboot-kernel-utils")
159 | elif distro.lower().__contains__("suse"):
160 | bash("zypper --non-interactive refresh") # sync repos
161 | bash("zypper --non-interactive install vboot parted pv xz") # cgpt is included in vboot-utils on fedora
162 | elif distro.lower().__contains__("fedora"):
163 | if distro.lower().__contains__("silverblue"):
164 | print_error("Silverblue requires a reboot to install the required packages. Containers will only "
165 | "work if started in privileged mode. Consider using a virtual machine instead.")
166 | if input("Proceed to installing packages into overlay? (y/N): ").lower() == "y":
167 | bash("rpm-ostree install vboot-utils parted pv xz")
168 | print_warning("Please reboot to apply packages")
169 | sys.exit(1) # exit as either the user needs to reboot or user chose not to install packages
170 | bash("dnf update --refresh -y") # sync repos
171 | bash("dnf install -y vboot-utils parted pv xz") # cgpt is included in vboot-utils on fedora
172 | else:
173 | print_warning("Script dependencies not found, please install the following packages with your package "
174 | "manager: which pv xz parted cgpt futility")
175 | sys.exit(1)
176 | else:
177 | print_warning("Skipping dependency check")
178 |
179 | # Check python version
180 | print_status("Checking Python version...")
181 | if sys.version_info < (3, 10): # python 3.10 or higher is required
182 | # Check if running under crostini and ask user to update python
183 | # Do not give this option on regular systems, as it may break the system
184 | try:
185 | with open("/sys/devices/virtual/dmi/id/product_name", "r") as file:
186 | product_name = file.read().strip()
187 | except FileNotFoundError:
188 | product_name = "" # wsl doesn't have dmi info
189 | if product_name == "crosvm" and path_exists("/usr/bin/apt"):
190 | user_answer = input("\033[92m" + "Python 3.10 or higher is required. Attempt to install? (Y/n)\n" +
191 | "\033[0m").lower()
192 | if user_answer in ["y", ""]:
193 | print_status("Switching to unstable channel")
194 | # switch to unstable channel
195 | with open("/etc/apt/sources.list", "r") as file:
196 | original_sources = file.readlines()
197 | sources = original_sources
198 | sources[1] = sources[1].replace("bullseye", "unstable")
199 | sources[1] = sources[1].replace("buster", "unstable") # Some crostinis are on buster
200 | with open("/etc/apt/sources.list", "w") as file:
201 | file.writelines(sources)
202 |
203 | # update and install python
204 | print_status("Installing Python 3.10")
205 | bash("apt-get update -y")
206 | bash("apt-get install -y python3")
207 | print_status("Python 3.10 installed")
208 |
209 | # revert to stable channel
210 | with open("/etc/apt/sources.list", "w") as file:
211 | file.writelines(original_sources)
212 |
213 | bash("apt-get update -y") # update cache back to stable channel
214 |
215 | print_status("Restarting the script...")
216 | # clear terminal, but keep any previous output so the user can scroll up to see it
217 | print("\033[H\033[2J", end="")
218 | os.execl(sys.executable, sys.executable, *sys.argv)
219 | print_error("Please run the script with python 3.10 or higher")
220 | sys.exit(1)
221 | # import other scripts after python version check is successful
222 | import build
223 | import cli_input
224 |
225 | # Check if running under crostini
226 | try:
227 | with open("/sys/devices/virtual/dmi/id/product_name", "r") as file:
228 | product_name = file.read().strip()
229 | except FileNotFoundError:
230 | product_name = "" # WSL has no dmi data
231 | if product_name == "crosvm":
232 | print_warning("Crostini detected. Preparing Crostini")
233 | # TODO: Translate to python
234 | try:
235 | bash("bash configs/crostini/setup-crostini.sh")
236 | except subprocess.CalledProcessError:
237 | print_error("Failed to prepare Crostini")
238 | print_error("Please run the Crostini specific instructions before running this script")
239 | print("https://eupnea-project.github.io/docs/extra/crostini#instructions")
240 | sys.exit(1)
241 |
242 | # clear terminal, but keep any previous output so the user can scroll up to see it
243 | print("\033[H\033[2J", end="")
244 |
245 | # parse arguments
246 | if args.dev_build:
247 | print_warning("Using dev release")
248 | if args.local_path:
249 | print_warning("Using local files")
250 | if args.verbose:
251 | print_warning("Verbosity increased")
252 | if args.no_shrink:
253 | print_warning("Image will not be shrunk")
254 | if args.image_size[0] != 10:
255 | print_warning(f"Image size overridden to {args.image_size[0]}GB")
256 |
257 | # override device if specified
258 | if not args.device_selection:
259 | user_input = cli_input.get_user_input(args.verbose_kernel, skip_device=True) # get user input
260 | user_input["device"] = "image"
261 | if args.device_override is not None:
262 | user_input["device"] = args.device_override # override device
263 | else:
264 | user_input = cli_input.get_user_input(args.verbose_kernel) # get normal user input
265 |
266 | # Clean system from previous depthboot builds
267 | print_status("Removing old depthboot build files")
268 | with contextlib.suppress(subprocess.CalledProcessError):
269 | bash("umount -lR /tmp/depthboot-build/*") # get rid of any mounts from previous generic iso builds
270 | rmdir("/tmp/depthboot-build")
271 |
272 | print_status("Unmounting old depthboot mounts if present")
273 | try:
274 | bash("umount -lf /mnt/depthboot") # just in case
275 | sleep(5) # wait for umount to finish
276 | bash("umount -lf /mnt/depthboot") # umount a second time, coz first time might not work
277 | except subprocess.CalledProcessError:
278 | print("Failed to unmount /mnt/depthboot, ignore")
279 | rmdir("/mnt/depthboot")
280 |
281 | rmfile("depthboot.img")
282 | rmfile("kernel.flags")
283 | rmfile(".stop_download_progress")
284 |
285 | # Check if there is enough space in /tmp
286 | avail_space = int(bash("BLOCK_SIZE=m df --output=avail /tmp").split("\n")[1][:-1]) # read tmp size in MB
287 | # TODO: Check if there is enough space on the device to build the image
288 | restore_tmp = False
289 |
290 | if user_input["device"] == "image" and avail_space < 13000 and not args.skip_size_check:
291 | print_warning("Not enough space in /tmp to build image. At least 13GB is required")
292 | # check if /tmp is a tmpfs mount
293 | if bash("df --output=fstype /tmp").__contains__("tmpfs"):
294 | user_answer = input("\033[92m" + "Remount /tmp to increase its size? (Y/n)\n" + "\033[0m").lower()
295 | if user_answer in ["y", ""]:
296 | print_status("Increasing size of /tmp")
297 | bash("mount -o remount,size=13G /tmp")
298 | print_status("Size of /tmp increased")
299 | restore_tmp = True
300 | else:
301 | print_error("Please free up space in /tmp")
302 | print("Use --skip-size-check to ignore this check")
303 | sys.exit(1)
304 | else:
305 | print_error("Allocate more storage to the container/vm if possible or clear /tmp or use another system")
306 | print("Use --skip-size-check to ignore this check")
307 | sys.exit(1)
308 |
309 | if user_input["distro_name"] == "generic":
310 | # check if unsquashfs is already installed with which
311 | try:
312 | bash("which unsquashfs")
313 | print_status("unsquashfs already installed, skipping")
314 | except subprocess.CalledProcessError:
315 | print_status("Installing unsquashfs")
316 | with open("/etc/os-release", "r") as os:
317 | distro = os.read()
318 | if distro.lower().__contains__(
319 | "arch"): # might accidentally catch architecture stuff, but needed to catch arch derivatives
320 | bash("pacman -Sy") # sync repos
321 | bash("pacman --noconfirm -S squashfs-tools")
322 | elif distro.lower().__contains__("void"):
323 | bash("xbps-install -y --sync")
324 | bash("xbps-install -y squashfs-tools")
325 | elif distro.lower().__contains__("ubuntu") or distro.lower().__contains__("debian"):
326 | bash("apt-get update -y") # sync repos
327 | bash("apt-get install -y squashfs-tools")
328 | elif distro.lower().__contains__("suse"):
329 | bash("zypper --non-interactive refresh") # sync repos
330 | bash("zypper --non-interactive install squashfs-tools")
331 | elif distro.lower().__contains__("fedora"):
332 | # Check if running on silverblue
333 | if distro.lower().__contains__("silverblue"):
334 | print_error("Silverblue requires a reboot to install the required packages. Containers will only "
335 | "work if started in privileged mode. Consider using a virtual machine instead.")
336 | if input("Proceed to installing packages into overlay? (y/N): ").lower() == "y":
337 | bash("rpm-ostree install squashfs-tools")
338 | print_warning("Please reboot to apply packages")
339 | sys.exit(1) # exit as either the user needs to reboot or user chose not to install packages
340 | bash("dnf update -y") # sync repos
341 | bash("dnf install -y squashfs-tools")
342 | else:
343 | print_warning("unsquashfs not found, please install it with your package manager")
344 | sys.exit(1)
345 |
346 | build.start_build(build_options=user_input, args=args)
347 | if restore_tmp: # restore /tmp size if it was changed
348 | print_status("Restoring size of /tmp")
349 | bash(f"mount -o remount,size={avail_space}M /tmp")
350 | sys.exit(0)
351 |
--------------------------------------------------------------------------------
/os_sizes.json:
--------------------------------------------------------------------------------
1 | {
2 | "arch_latest": {
3 | "budgie": 4.9,
4 | "cinnamon": 2.5,
5 | "cli": 3.2,
6 | "deepin": -1.6,
7 | "gnome": 5.7,
8 | "kde": 5.3,
9 | "lxqt": 4.7,
10 | "xfce": 4.5
11 | },
12 | "debian_stable": {
13 | "budgie": -1.2,
14 | "cinnamon": 7.1,
15 | "cli": 2.4,
16 | "gnome": 5.8,
17 | "kde": 7.3,
18 | "lxqt": 6.7,
19 | "xfce": 5.5
20 | },
21 | "fedora_39": {
22 | "budgie": 3.2,
23 | "cinnamon": 7.3,
24 | "cli": 3.0,
25 | "deepin": 6.5,
26 | "gnome": 6.8,
27 | "kde": 6.1,
28 | "lxqt": 5.5,
29 | "xfce": 4.9
30 | },
31 | "fedora_40": {
32 | "budgie": 3.4,
33 | "cinnamon": 7.4,
34 | "cli": 3.3,
35 | "deepin": -1.6,
36 | "gnome": 6.8,
37 | "kde": 6.2,
38 | "lxqt": 5.8,
39 | "xfce": 5.2
40 | },
41 | "fedora_average": 3.1,
42 | "pop-os_22.04": {
43 | "cosmic-gnome": 9.3
44 | },
45 | "ubuntu_22.04": {
46 | "budgie": 5.6,
47 | "cinnamon": 7.0,
48 | "cli": 3.9,
49 | "deepin": 7.1,
50 | "gnome": 5.5,
51 | "kde": 5.5,
52 | "lxqt": 4.6,
53 | "xfce": 5.1
54 | },
55 | "ubuntu_23.10": {
56 | "budgie": 5.4,
57 | "cinnamon": 6.9,
58 | "cli": 3.4,
59 | "deepin": -1.7,
60 | "gnome": 5.7,
61 | "kde": 5.4,
62 | "lxqt": 6.5,
63 | "xfce": 5.4
64 | },
65 | "ubuntu_average": 3.6
66 | }
--------------------------------------------------------------------------------