import argparse import json import os import sys from pathlib import Path from tempfile import TemporaryDirectory from .config import ( REMOTE_MODES, InstallError, check_password, parse_plan, platform_settings, read_password, read_plan, ) from .engine import Installer from .interactive import interactive_plan, local_path from .terminal import PlainTerminal, configure_terminal def get_password(terminal): while True: try: password = check_password( terminal.password("Administrator password") ) if ( terminal.password("Repeat the administrator password") == password ): return password raise InstallError("The administrator passwords differ.") except InstallError as error: if not sys.stdin.isatty(): raise terminal.error(error) def export_parameters(plan, password_path): panel = {"hostname": plan.hostname, "access": plan.access} if plan.access == "tls": panel.update(certificate=plan.certificate, key=plan.key) elif plan.access == "proxy": panel.update( origin_ip=plan.origin_ip, origin_port=plan.origin_port, proxy_ip=plan.proxy_ip, ) admin = {"username": plan.admin_username, "email": plan.admin_email} if password_path: admin["password_file"] = password_path parameters = { "panel": panel, "admin": admin, "hosting": plan.hosting.parameters(), } for name, role in (("dns", plan.dns), ("mail", plan.mail)): fields = parameters[name] = {"mode": role.mode} if role.mode in REMOTE_MODES: fields.update( host=role.host, host_key=role.host_key, port=role.port ) if role.mode == "remote-install": fields.update( ssh_user=role.ssh_user, ssh_identity=role.ssh_identity ) if name == "mail" and role.mail_hostname: host_key = "host" if role.mode == "local" else "mail_hostname" fields[host_key] = role.mail_hostname if name == "mail" and role.mode in {"local", "remote-install"}: fields["tls"] = role.tls if role.tls == "provided": fields.update(certificate=role.certificate, key=role.key) return parameters def save_interactive_plan(plan, password_path, terminal=None): terminal = terminal or PlainTerminal() while True: destination = terminal.prompt( "TOML file path", hint="Leave blank to install without saving a copy.", ) if not destination: return try: path = Path(local_path(destination)) exists = os.path.lexists(path) if ( exists and terminal.choose(f"Replace {path}", ("yes", "no"), "no") != "yes" ): continue write_interactive_plan(path, plan, password_path, replace=exists) except (OSError, InstallError) as error: terminal.error(f"Could not save the installation plan. {error}") else: break return path def interactive_configuration(terminal, password_path): plan = interactive_plan(terminal) if plan is None: return None terminal.step = None terminal.heading("Administrator password") if password_path: while True: try: password = read_password(password_path) break except InstallError as error: terminal.error(error) password_path = terminal.prompt( "Administrator password file", password_path ) else: password = get_password(terminal) terminal.heading("Save installation settings") if not password_path: terminal.show( "Provide a private administrator password file " "when reusing the plan." ) saved = save_interactive_plan(plan, password_path, terminal) return plan, password, saved def write_interactive_plan(path, plan, password_path, *, replace): with TemporaryDirectory(dir=path.parent) as directory: temporary = Path(directory) / "installation.toml" with temporary.open("w", encoding="utf-8") as output: temporary.chmod(0o600) for section, fields in export_parameters( plan, password_path ).items(): output.write(f"[{section}]\n") for name, value in fields.items(): encoded = json.dumps(value, ensure_ascii=False).replace( "\x7f", "\\u007f" ) output.write(f"{name} = {encoded}\n") output.write("\n") if replace: os.replace(temporary, path) else: os.link(temporary, path) def install(plan, password, *, interactive): terminal = PlainTerminal() if interactive: terminal.heading("Installing Coulobre") while True: try: Installer( plan, password, lambda message: print(message, flush=True), heartbeat=sys.stdout.isatty(), ).install() except (InstallError, OSError, ValueError) as error: if not interactive: raise print(f"Coulobre installer: {error}", file=sys.stderr) print( "Fix the reported problem and retry with these settings. " "Coulobre resumes the same installation." ) if ( terminal.choose("Installation", ("retry", "exit"), "exit") == "exit" ): return 1 else: return 0 def main(argv=None): parser = argparse.ArgumentParser( description="Install Coulobre Panel on a fresh server." ) modes = parser.add_mutually_exclusive_group() modes.add_argument( "--interactive", action="store_true", help="Open the guided terminal wizard (the default).", ) modes.add_argument( "--config", metavar="FILE", help="Read installation parameters from TOML.", ) modes.add_argument( "--web", action="store_true", help="Open the loopback setup wizard." ) parser.add_argument( "--admin-password-file", help="Read the administrator password from a private file.", ) parser.add_argument( "--port", type=int, default=8765, help="Loopback port for the web wizard.", ) parser.add_argument( "--check", action="store_true", help="Validate parameters without installing.", ) options = parser.parse_args(argv) if options.check and not options.config: parser.error("--check requires --config.") if options.port != 8765 and not options.web: parser.error("--port requires --web.") try: platform_settings() if not options.check and os.geteuid() != 0: raise InstallError("Run the installer as root.") if options.web: from .web import serve_wizard if not options.admin_password_file: parser.error("--web requires --admin-password-file.") return serve_wizard( read_password(options.admin_password_file), options.port ) if options.config: data = read_plan(options.config) plan = parse_plan(data) password_path = options.admin_password_file or data["admin"].get( "password_file" ) if not password_path: raise InstallError( "Specify the administrator password file in [admin]." ) password = read_password(password_path) else: configured = configure_terminal( lambda terminal: interactive_configuration( terminal, options.admin_password_file ) ) if configured is None: return 0 plan, password, saved = configured if saved is not None: print(f"Saved installation settings to {saved}.") if options.check: print(plan.description()) return 0 return install(plan, password, interactive=not options.config) except (InstallError, OSError, ValueError) as error: print(f"Coulobre installer: {error}", file=sys.stderr) return 1 except (EOFError, KeyboardInterrupt): print("\nInstallation input was interrupted.", file=sys.stderr) return 1