1/*
2 * Copyright 2013-2018, Haiku, Inc. All Rights Reserved.
3 * Distributed under the terms of the MIT License.
4 *
5 * Authors:
6 *		Ingo Weinhold <ingo_weinhold@gmx.de>
7 *		Andrew Lindesay <apl@lindesay.co.nz>
8 */
9
10
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14
15#include <package/RepositoryConfig.h>
16#include <package/RepositoryInfo.h>
17
18
19#define DIE(error, ...)								\
20	do {											\
21		fprintf(stderr, "Error: " __VA_ARGS__);		\
22		fprintf(stderr, ": %s\n", strerror(error));	\
23		exit(1);									\
24	} while (false)
25
26#define DIE_ON_ERROR(error, ...)		\
27	do {								\
28		status_t _error = error;		\
29		if (error != B_OK)				\
30			DIE(_error, __VA_ARGS__);	\
31	} while (false)
32
33
34static const char* sProgramName = "create_repository_config";
35
36
37void
38print_usage_and_exit(bool error)
39{
40	fprintf(error ? stderr : stdout,
41		"Usage: %s [ <URL> ] <repository info> <repository config>\n"
42		"Creates a repository config file from a given repository info and\n"
43		"the base URL (the directory in which the \"repo\", \"repo.info\',\n"
44		"and \"repo.sha256 files can be found). If the URL is not specified,\n"
45		"the one from the repository info is used.",
46		sProgramName);
47	exit(error ? 1 : 0);
48}
49
50
51int
52main(int argc, const char* const* argv)
53{
54	if (argc < 3 || argc > 4) {
55		if (argc == 2
56			&& (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
57				print_usage_and_exit(false);
58		}
59		print_usage_and_exit(true);
60	}
61
62	int argi = 1;
63	const char* baseUrl = argc == 4 ? argv[argi++] : NULL;
64	const char* infoPath = argv[argi++];
65	const char* configPath = argv[argi++];
66
67	// read the info
68	BPackageKit::BRepositoryInfo repoInfo;
69	DIE_ON_ERROR(repoInfo.SetTo(infoPath),
70		"failed to read repository info file \"%s\"", infoPath);
71
72	if (baseUrl == NULL) {
73		if (repoInfo.BaseURL().IsEmpty()) {
74			// legacy (pre-beta1) repositories may have a single "URL"
75			// field acting both as baseURL and identifier.
76			baseUrl = repoInfo.Identifier();
77		} else
78			baseUrl = repoInfo.BaseURL();
79	}
80
81	// init and write the config
82	BPackageKit::BRepositoryConfig repoConfig;
83	repoConfig.SetName(repoInfo.Name());
84	repoConfig.SetBaseURL(baseUrl);
85	repoConfig.SetIdentifier(repoInfo.Identifier());
86	repoConfig.SetPriority(repoInfo.Priority());
87	DIE_ON_ERROR(repoConfig.Store(configPath),
88		"failed to write repository config file \"%s\"", configPath);
89
90	return 0;
91}
92