#!/usr/bin/env python3

import base64
import json
import os
import shutil
import subprocess
import sys
import syslog
import tempfile

IMAGES_DIRECTORY           = '/images'
ADDONS_OUTPUT_DIRECTORY    = f"{IMAGES_DIRECTORY}/boot/addons"
SECURE_BOOT_KEYS_DIRECTORY = '/run/puavo/secure-boot-keys'

ADDON_PATH                     = f"{ADDONS_OUTPUT_DIRECTORY}/extra.commandline.addon.efi"
DEVICE_SECURE_BOOT_CERTIFICATE = f"{SECURE_BOOT_KEYS_DIRECTORY}/secure-boot.pem"
DEVICE_SECURE_BOOT_PRIVATE_KEY = f"{ADDONS_OUTPUT_DIRECTORY}/secure-boot.priv"
KERNEL_COMMANDLINE_FILE        = f"{ADDONS_OUTPUT_DIRECTORY}/commandline"

# The server sends the addon it built and the policy that allows the TPM
# to sign exactly that addon.
AUTHORIZATION_BUNDLE = f"{ADDONS_OUTPUT_DIRECTORY}/authorization.json"

# TODO(command-line-server-key): Remove with the placeholder keys, once
# Puppet configures the server key.
PLACEHOLDER_SERVER_PRIVATE_KEY = '/run/puavo/command-line/server.priv'

PUAVO_CORE_LIBDIR    = '/usr/lib/puavo-core'
PUAVO_INSTALL_LIBDIR = '/usr/lib/puavo-ltsp-install'


def log_info(message: str):
  syslog.syslog(syslog.LOG_INFO, message)


def log_error(message: str):
  syslog.syslog(syslog.LOG_ERR, message)


def run_command(*args, check: bool = True, capture: bool = True):
  return subprocess.run(
    args,
    check=check,
    text=True,
    capture_output=capture,
  )


def replace_if_changed(destination: str, source: str):
  try:
    import filecmp
    if (
      os.path.exists(destination) and
        filecmp.cmp(destination, source, shallow=False)
    ):
      os.remove(source)
      return
  except Exception:
    # Fall through to moving the file
    pass

  shutil.move(source, destination)


def sign_with_disk_key(section_value: str, output: str):
  # Build UKI addon containing only a .cmdline section
  try:
    run_command(
      'ukify', 'build',
      f'--secureboot-private-key={DEVICE_SECURE_BOOT_PRIVATE_KEY}',
      f'--secureboot-certificate={DEVICE_SECURE_BOOT_CERTIFICATE}',
      f'--section=.cmdline:{section_value}',
      f'--output={output}'
    )
  except subprocess.CalledProcessError as error:
    log_error(f"failed to build command-line addon (exit code {error.returncode}): {error.stderr.strip()}")
    raise RuntimeError("failed to build command-line addon")


def read_bundle_commandline(bundle: str) -> str:
  with open(bundle) as file:
    addon = base64.b64decode(json.load(file)['addon'])

  with tempfile.NamedTemporaryFile() as image, \
       tempfile.NamedTemporaryFile() as section:
    image.write(addon)
    image.flush()
    run_command(
      'objcopy', '-O', 'binary', '--only-section=.cmdline', image.name,
      section.name
    )
    return section.read().rstrip(b'\0').decode()


def authorize_with_placeholder(section_value: str, bundle: str):
  # Authorizes the command-line as the server would, one counter value
  # ahead so it ends the earlier authorizations.
  with tempfile.TemporaryDirectory() as directory:
    addon = f"{directory}/addon.efi"
    try:
      run_command(
        'ukify', 'build', f'--section=.cmdline:{section_value}',
        f'--output={addon}'
      )
      counter = run_command(
        f"{PUAVO_CORE_LIBDIR}/puavo-command-line-manager-counter"
      ).stdout.strip()
      run_command(
        f"{PUAVO_CORE_LIBDIR}/puavo-command-line-manager-authorize",
        addon, DEVICE_SECURE_BOOT_CERTIFICATE, PLACEHOLDER_SERVER_PRIVATE_KEY,
        str(int(counter) + 1), bundle
      )
    except subprocess.CalledProcessError as error:
      log_error(f"failed to authorize with the placeholder key (exit code {error.returncode}): {error.stderr.strip()}")
      raise RuntimeError("failed to authorize command-line addon")


def sign_with_tpm(section_value: str, output: str):
  with tempfile.TemporaryDirectory() as directory:
    bundle = AUTHORIZATION_BUNDLE
    if os.path.isfile(PLACEHOLDER_SERVER_PRIVATE_KEY):
      bundle = f"{directory}/authorization.json"
      authorize_with_placeholder(section_value, bundle)

    sign_bundle(bundle, section_value, output)


def sign_bundle(bundle: str, section_value: str, output: str):
  if not os.path.isfile(bundle):
    raise RuntimeError(f"no server authorization in {bundle}")

  # An authorization for an earlier command-line must not be installed.
  authorized_commandline = read_bundle_commandline(bundle)
  if authorized_commandline != section_value:
    raise RuntimeError(
      f"server authorized '{authorized_commandline}', not '{section_value}'"
    )

  try:
    run_command(
      f"{PUAVO_CORE_LIBDIR}/puavo-command-line-manager-sign",
      SECURE_BOOT_KEYS_DIRECTORY, bundle, output
    )
    run_command('sbverify', '--cert', DEVICE_SECURE_BOOT_CERTIFICATE, output)
  except subprocess.CalledProcessError as error:
    log_error(f"failed to sign command-line addon (exit code {error.returncode}): {error.stderr.strip()}")
    raise RuntimeError("failed to sign command-line addon")


def build_commandline_addon(commandline: str):
  os.makedirs(ADDONS_OUTPUT_DIRECTORY, exist_ok=True)

  if not os.path.isfile(DEVICE_SECURE_BOOT_CERTIFICATE):
    raise RuntimeError(
      f"device Secure Boot certificate is missing: {DEVICE_SECURE_BOOT_CERTIFICATE}"
    )

  # Systemd-stub rejects an actually empty section, use a single space
  # in that case
  section_value = commandline if commandline.strip() != '' else ' '

  temporary_commandline_addon = f"{ADDON_PATH}.tmp"

  # A key on disk signs directly. Fully installed encrypted devices have
  # none, and their TPM signs only what the server authorized.
  if os.path.isfile(DEVICE_SECURE_BOOT_PRIVATE_KEY):
    sign_with_disk_key(section_value, temporary_commandline_addon)
  else:
    sign_with_tpm(section_value, temporary_commandline_addon)

  replace_if_changed(ADDON_PATH, temporary_commandline_addon)


def update_kernel_commandline(expected_kernel_commandline: str) -> int:
  current_kernel_commandline = None
  try:
    with open(KERNEL_COMMANDLINE_FILE, 'r') as file:
      current_kernel_commandline = file.read().strip()
  except FileNotFoundError:
    pass

  if expected_kernel_commandline == current_kernel_commandline:
    log_info("kernel command-line unchanged, nothing to do")
    return 0

  log_info("kernel command-line changed, rebuilding addon")
  log_info(f"old: {current_kernel_commandline}")
  log_info(f"new: {expected_kernel_commandline}")

  build_commandline_addon(expected_kernel_commandline)

  # Install the new command-line addon
  try:
    run_command(
      'puavo-install-and-update-uki-images',
      '--images-dir', IMAGES_DIRECTORY
    )
  except subprocess.CalledProcessError as error:
    log_error(error.stderr.strip() or "failed to install command line addon")
    return 1

  # Update the command line file with the new commandline
  try:
    with open(KERNEL_COMMANDLINE_FILE, 'w') as file:
      file.write(expected_kernel_commandline)
  except IOError as error:
    log_error(f"failed to write kernel command-line file: {error}")
    return 1

  log_info("kernel command-line addon updated")
  return 0


def clean_temporary_files():
  for path in [f"{ADDON_PATH}.tmp", f"{KERNEL_COMMANDLINE_FILE}.tmp"]:
    try:
      os.remove(path)
    except FileNotFoundError:
      pass


def main(new_kernel_commandline: str) -> int:
  try:
    return update_kernel_commandline(new_kernel_commandline.strip())
  except Exception as error:
    log_error(str(error))
    clean_temporary_files()
    return 1


syslog.openlog('puavo-install-uki-commandline-addon',
               logoption=syslog.LOG_PERROR)

if len(sys.argv) != 2:
  sys.exit(1)

new_kernel_commandline = sys.argv[1]

if __name__ == '__main__':
  exitcode = main(new_kernel_commandline)
  syslog.closelog()
  sys.exit(exitcode)
