Bootstrap: docker
From: {{ build.image }}
Stage: build

%post
{% if os_packages_build.list %}
  # Update, install and cleanup of system packages needed at build-time
  {% if os_package_update %}
  {{ os_packages_build.update }}
  {% endif %}
  {{ os_packages_build.install }} {{ os_packages_build.list | join | replace('\n', ' ') }}
  {{ os_packages_build.clean }}

{% endif %}
  # Create the manifest file for the installation in /opt/spack-environment
  mkdir {{ paths.environment }} && cd {{ paths.environment }}
  cat << EOF > spack.yaml
{{ manifest }}
EOF

  # Install all the required software
  . /opt/spack/share/spack/setup-env.sh
  spack env activate .
  spack install {% if monitor.enabled %}--monitor {% if monitor.prefix %}--monitor-prefix {{ monitor.prefix }} {% endif %}{% if monitor.tags %}--monitor-tags {{ monitor.tags }} {% endif %}{% if monitor.keep_going %}--monitor-keep-going {% endif %}{% if monitor.host %}--monitor-host {{ monitor.host }} {% endif %}{% if monitor.disable_auth %}--monitor-disable-auth {% endif %}{% endif %}--fail-fast
  spack gc -y
  spack env deactivate
  spack env activate --sh -d . >> {{ paths.environment }}/environment_modifications.sh
{% if strip %}

  # Strip the binaries to reduce the size of the image
  find -L {{ paths.view }}/* -type f -exec readlink -f '{}' \; | \
    xargs file -i | \
    grep 'charset=binary' | \
    grep 'x-executable\|x-archive\|x-sharedlib' | \
    awk -F: '{print $1}' | xargs strip -s
{% endif %}
{% if extra_instructions.build %}
{{ extra_instructions.build }}
{% endif %}

{% if apps %}
{% for application, help_text in apps.items() %}

%apprun {{ application }}
    exec /opt/view/bin/{{ application }} "$@"

%apphelp {{ application }}
    {{help_text }}
{% endfor %}
{% endif %}

Bootstrap: docker
From: {{ run.image }}
Stage: final

%files from build
  {{ paths.environment }} /opt
  {{ paths.store }} /opt
  {{ paths.view }} /opt
  {{ paths.environment }}/environment_modifications.sh {{ paths.environment }}/environment_modifications.sh

%post
{% if os_packages_final.list %}
  # Update, install and cleanup of system packages needed at run-time
  {% if os_package_update %}
  {{ os_packages_final.update }}
  {% endif %}
  {{ os_packages_final.install }} {{ os_packages_final.list | join | replace('\n', ' ') }}
  {{ os_packages_final.clean }}
{% endif %}
  # Modify the environment without relying on sourcing shell specific files at startup
  cat {{ paths.environment }}/environment_modifications.sh >> $SINGULARITY_ENVIRONMENT
{% if extra_instructions.final %}
{{ extra_instructions.final }}
{% endif %}
{% if runscript %}

%runscript
{{ runscript }}
{% endif %}
{% if startscript %}

%startscript
{{ startscript }}
{% endif %}
{% if test %}

%test
{{ test }}
{% endif %}
{% if help %}

%help
{{ help }}
{% endif %}
{% if labels %}

%labels
{% for label, value in labels.items() %}
  {{ label }} {{ value }}
{% endfor %}
{% endif %}
