#!/bin/bash
set -e

echo "Setting up s390x headers..."

# Create directories
mkdir -p /usr/s390x-linux-gnu/include
mkdir -p /usr/s390x-linux-gnu/sys-include

# Download headers manually
cd /tmp
echo "Downloading glibc headers..."
curl -L -o glibc-headers.rpm "https://kojipkgs.fedoraproject.org/packages/glibc/2.38/19.fc39/s390x/glibc-headers-2.38-19.fc39.s390x.rpm" || {
    echo "Failed to download from koji, trying mirror..."
    curl -L -o glibc-headers.rpm "https://mirrors.rit.edu/fedora/fedora-secondary/updates/39/Everything/s390x/Packages/g/glibc-headers-2.38-19.fc39.s390x.rpm"
}

echo "Downloading kernel headers..."
curl -L -o kernel-headers.rpm "https://kojipkgs.fedoraproject.org/packages/kernel-headers/6.5.5/300.fc39/s390x/kernel-headers-6.5.5-300.fc39.s390x.rpm" || {
    echo "Failed to download from koji, trying mirror..."
    curl -L -o kernel-headers.rpm "https://mirrors.rit.edu/fedora/fedora-secondary/releases/39/Everything/s390x/os/Packages/k/kernel-headers-6.5.5-300.fc39.s390x.rpm"
}

# Extract headers
echo "Extracting headers..."
rpm2cpio glibc-headers.rpm | cpio -id 2>/dev/null
rpm2cpio kernel-headers.rpm | cpio -id 2>/dev/null

# Copy headers
echo "Installing headers..."
cp -r usr/include/* /usr/s390x-linux-gnu/include/ || true
cp -r usr/include/* /usr/s390x-linux-gnu/sys-include/ || true

# Also set up in the standard cross-compile location
mkdir -p /usr/lib/gcc/s390x-linux-gnu/13/include-fixed
cp -r usr/include/* /usr/lib/gcc/s390x-linux-gnu/13/include-fixed/ || true

# Clean up
rm -rf /tmp/*.rpm /tmp/usr

echo "Headers installed successfully!"
