# SPDX-FileCopyrightText: 2020 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ pkgs, ... }:
let
  origImageArgs = builtins.fromJSON (builtins.readFile ./image.json);
  origImage = pkgs.dockerTools.pullImage origImageArgs;

  name = origImageArgs.imageName;
  tag = "${origImageArgs.finalImageTag}-lukegb";
in pkgs.dockerTools.buildImage rec {
  inherit name tag;
  fromImage = origImage;
  fromImageName = origImageArgs.finalImageName;
  fromImageTag = origImageArgs.finalImageTag;
  diskSize = 10216;
  runAsRoot = ''
    #!{pkgs.runtimeShell}
    cat <<"EOF" >/sshd_ca.pub
    ${builtins.readFile ../../../ops/secrets/client-ca.pub}
    EOF
    cat <<"EOF" >/assets/wrapper_wrapper
    #!/bin/bash
    /usr/bin/id hg || /usr/sbin/useradd -g $(id -u git) -u $(id -g git) -o -d /var/opt/gitlab -p "*" hg
    /usr/bin/grep "AllowUsers git hg" /assets/sshd_config || /bin/sed -i "s/AllowUsers git/AllowUsers git hg/" /assets/sshd_config
    /usr/bin/cat <<"EOC" >>/assets/sshd_config
    TrustedUserCAKeys /sshd_ca.pub
    Match User git
      AuthorizedPrincipalsCommandUser root
      AuthorizedPrincipalsCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-principals-check lukegb lukegb
    Match User hg
      AuthorizedPrincipalsCommandUser root
      AuthorizedPrincipalsCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-principals-check lukegb lukegb
    EOC
    exec /assets/wrapper "$@"
    EOF
    chmod ugo=rx /assets/wrapper_wrapper
  '';
  config.Cmd = ["/assets/wrapper_wrapper"];
} // {
  meta = { inherit name tag origImage; };
}