---
- name: Build Arch Linux packages on z/VM s390x
  hosts: zvm-build
  become: yes
  vars:
    build_user: archbuild
    arch_root: /opt/arch-s390x
    
  tasks:
    - name: Ensure latest build script is deployed
      copy:
        src: files/manual-build.sh
        dest: "{{ arch_root }}/tools/manual-build.sh"
        owner: "{{ build_user }}"
        group: "{{ build_user }}"
        mode: '0755'

    - name: Build linux-api-headers package
      become_user: "{{ build_user }}"
      shell: |
        export ARCH_ROOT={{ arch_root }}
        export BUILDDIR={{ arch_root }}/build
        export PATH="{{ arch_root }}/sysroot/usr/bin:${PATH}"
        {{ arch_root }}/tools/manual-build.sh linux-api-headers
      args:
        chdir: /home/{{ build_user }}
        creates: "{{ arch_root }}/sysroot/usr/include/linux"
      register: build_result

    - name: Display build results
      debug:
        var: build_result.stdout_lines

    - name: Check installed headers
      become_user: "{{ build_user }}"
      shell: "ls -la {{ arch_root }}/sysroot/usr/include/ | head -10"
      register: headers_check

    - name: Display installed headers
      debug:
        msg:
          - "Installed kernel headers:"
          - "{{ headers_check.stdout_lines }}"

    - name: Build glibc package
      become_user: "{{ build_user }}"
      shell: |
        export ARCH_ROOT={{ arch_root }}
        export BUILDDIR={{ arch_root }}/build
        export PATH="{{ arch_root }}/sysroot/usr/bin:${PATH}"
        export C_INCLUDE_PATH="{{ arch_root }}/sysroot/usr/include"
        export CPPFLAGS="-I{{ arch_root }}/sysroot/usr/include"
        {{ arch_root }}/tools/manual-build.sh glibc
      args:
        chdir: /home/{{ build_user }}
        creates: "{{ arch_root }}/sysroot/usr/lib/libc.so"
      register: glibc_result
      timeout: 3600

    - name: Display glibc build results
      debug:
        var: glibc_result.stdout_lines
      when: glibc_result is defined

    - name: Check glibc installation
      become_user: "{{ build_user }}"
      shell: "ls -la {{ arch_root }}/sysroot/usr/lib/libc* || echo 'No libc files found'"
      register: glibc_check

    - name: Display glibc files
      debug:
        msg:
          - "Installed glibc files:"
          - "{{ glibc_check.stdout_lines }}"