#!/usr/bin/env python3 """Create the local administrator and keep its random password out of logs.""" import json import os from pathlib import Path import secrets import subprocess base = Path(__file__).resolve().parent.parent engine = os.environ.get('ENGINE', 'podman') cli = [engine, 'exec', '--user', 'git', 'devsecops-gitea', 'gitea', '--config', '/data/gitea/conf/app.ini', 'admin', 'user'] path = base / 'credentials.json' if not path.exists(): credentials = {'url': 'http://localhost:3000', 'username': 'gitea-admin', 'password': secrets.token_urlsafe(32)} fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(fd, 'w') as f: json.dump(credentials, f, indent=2) with path.open() as f: credentials = json.load(f) users = subprocess.check_output(cli + ['list'], text=True) if not any(credentials['username'] in line.split() for line in users.splitlines()): subprocess.run(cli + ['create', '--username', credentials['username'], '--password', credentials['password'], '--email', 'gitea-admin@localhost.localdomain', '--admin', '--must-change-password=false'], check=True, stdout=subprocess.DEVNULL) print(f'Administrator ready. Read the private credentials file: {path}')