1#!/usr/bin/env python3
2#
3# Copyright 2019 The Hafnium Authors.
4#
5# Use of this source code is governed by a BSD-style
6# license that can be found in the LICENSE file or at
7# https://opensource.org/licenses/BSD-3-Clause.
8
9"""Generate an initial RAM disk for a Linux VM."""
10
11import argparse
12import os
13import shutil
14import subprocess
15import sys
16
17def Main():
18    parser = argparse.ArgumentParser()
19    parser.add_argument("--staging", required=True)
20    parser.add_argument("--output", required=True)
21    args = parser.parse_args()
22    # Package files into an initial RAM disk.
23    with open(args.output, "w") as initrd:
24        # Move into the staging directory so the file names taken by cpio don't
25        # include the path.
26        os.chdir(args.staging)
27        staged_files = [os.path.join(root, filename)
28          for (root, dirs, files) in os.walk(".") for filename in files + dirs]
29        cpio = subprocess.Popen(
30            ["cpio", "--create", "--format=newc"],
31            stdin=subprocess.PIPE,
32            stdout=initrd,
33            stderr=subprocess.PIPE)
34        cpio.communicate(input="\n".join(staged_files).encode("utf-8"))
35    return 0
36
37
38if __name__ == "__main__":
39    sys.exit(Main())
40