1 /*	$OpenBSD: installboot.c,v 1.4 2014/01/19 04:14:22 jsing Exp $	*/
2 
3 /*
4  * Copyright (c) 2012, 2013 Joel Sing <jsing@openbsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <err.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <util.h>
26 
27 #include "installboot.h"
28 
29 int	nowrite;
30 int	stages;
31 int	verbose;
32 
33 char	*root = "/";
34 char	*stage1;
35 char	*stage2;
36 
37 static __dead void
38 usage(void)
39 {
40 	extern char *__progname;
41 
42 	fprintf(stderr, "usage: %s [-nv] [-r root] disk [stage1%s]\n",
43 	    __progname, (stages >= 2) ? " [stage2]" : "");
44 
45 	exit(1);
46 }
47 
48 int
49 main(int argc, char **argv)
50 {
51 	char *dev, *realdev;
52 	int devfd;
53 	char opt;
54 
55 	md_init();
56 
57 	while ((opt = getopt(argc, argv, "nr:v")) != -1) {
58 		switch (opt) {
59 		case 'n':
60 			nowrite = 1;
61 			break;
62 		case 'r':
63 			root = strdup(optarg);
64 			if (root == NULL)
65 				err(1, "strdup");
66 			break;
67 		case 'v':
68 			verbose = 1;
69 			break;
70 		default:
71 			usage();
72 		}
73 	}
74 
75 	argc -= optind;
76 	argv += optind;
77 
78 	if (argc < 1 || argc > stages + 1)
79 		usage();
80 
81 	dev = argv[0];
82 	if (argc > 1)
83 		stage1 = argv[1];
84 	if (argc > 2)
85 		stage2 = argv[2];
86 
87 	/* Prefix stages with root, unless they were user supplied. */
88 	if (verbose)
89 		fprintf(stderr, "Using %s as root\n", root);
90 	if (argc <= 1 && stage1 != NULL)
91 		stage1 = fileprefix(root, stage1);
92 	if (argc <= 2 && stage2 != NULL)
93 		stage2 = fileprefix(root, stage2);
94 
95 	if ((devfd = opendev(dev, (nowrite ? O_RDONLY : O_RDWR), OPENDEV_PART,
96 	    &realdev)) < 0)
97 		err(1, "open: %s", realdev);
98 
99         if (verbose) {
100 		fprintf(stderr, "%s bootstrap on %s\n",
101 		    (nowrite ? "would install" : "installing"), realdev);
102 		if (stage1)
103 			fprintf(stderr, "using first-stage %s", stage1);
104 		if (stage2)
105 			fprintf(stderr, ", second-stage %s", stage2);
106 		fprintf(stderr, "\n");
107 	}
108 
109 	md_loadboot();
110 
111 #ifdef SOFTRAID
112 	sr_installboot(devfd, dev);
113 #else
114 	md_installboot(devfd, realdev);
115 #endif
116 
117 	return 0;
118 }
119