#!/bin/bash
# ThinkPad X1 Carbon Gen 14 (21V7) - Debian Trixie Setup Script
# Fixes: display (black screen), audio (no sound)
# Run as root after a fresh Debian Trixie install.
#
# The script will:
#   1. Install the 7.0.4 backports kernel and reboot if needed
#   2. Fix display (Intel Panther Lake / xe driver)
#   3. Fix audio (CS42L45 / SDCA)
#
# Run it twice if it reboots: once to install the kernel, once to do everything else.

set -e

echo "=== ThinkPad X1 Carbon Gen 14 - Debian Trixie Setup ==="
echo "Running as: $(whoami), kernel: $(uname -r)"

if [ "$(id -u)" != "0" ]; then
    echo "Must be run as root"
    exit 1
fi

### 0. Install backports kernel if not already running it
echo ""
echo "--- Checking kernel version ---"

# Add trixie-backports if not already present
if ! grep -rq 'trixie-backports' /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null; then
    echo "Adding trixie-backports repository..."
    cat > /etc/apt/sources.list.d/backports.list << 'EOF'
deb http://deb.debian.org/debian trixie-backports main
deb-src http://deb.debian.org/debian trixie-backports main
EOF
    apt update
fi

# Check if we're already on the backports kernel (7.x)
KVER_MAJOR=$(uname -r | cut -d. -f1)
if [ "$KVER_MAJOR" -lt 7 ]; then
    echo "Installing backports kernel (current: $(uname -r))..."
    apt install -y -t trixie-backports linux-image-amd64 linux-headers-amd64
    echo ""
    echo "=== Backports kernel installed. Please reboot and run this script again. ==="
    echo "    reboot"
    exit 0
else
    echo "Already running backports kernel $(uname -r), continuing..."
fi

### 1. Install dependencies
echo ""
echo "--- Installing dependencies ---"
apt install -y git wget b4 flex bison libelf-dev zstd pipewire pipewire-pulse wireplumber pulseaudio-utils \
    linux-headers-$(uname -r) build-essential

### 2. Fix GRUB - add acpi_backlight=native
echo ""
echo "--- Fixing GRUB parameters ---"
if ! grep -q 'acpi_backlight=native' /etc/default/grub; then
    sed -i 's/GRUB_CMDLINE_LINUX_DEFAULT="\(.*\)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 acpi_backlight=native"/' /etc/default/grub
fi
update-grub

### 3. Fix GDM - set INTEL_FORCE_PROBE for Mesa
echo ""
echo "--- Fixing GDM environment for Intel Panther Lake GPU ---"
mkdir -p /etc/systemd/system/gdm.service.d
cat > /etc/systemd/system/gdm.service.d/override.conf << 'EOF'
[Service]
Environment=INTEL_FORCE_PROBE=*
EOF
# Also set system-wide for other display managers
if ! grep -q 'INTEL_FORCE_PROBE' /etc/environment; then
    echo 'INTEL_FORCE_PROBE=*' >> /etc/environment
fi

### 4. Clone linux-firmware repo and install missing firmware
echo ""
echo "--- Cloning linux-firmware repository ---"
FWDIR="/root/linux-firmware"
if [ ! -d "$FWDIR" ]; then
    git clone --depth=1 https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git "$FWDIR"
else
    git -C "$FWDIR" pull
fi

echo "--- Installing GPU firmware (xe/ptl_guc_70.bin) ---"
mkdir -p /lib/firmware/xe
cp "$FWDIR/xe/ptl_guc_70.bin" /lib/firmware/xe/

echo "--- Installing display firmware (i915/xe3lpd_dmc.bin) ---"
mkdir -p /lib/firmware/i915
cp "$FWDIR/i915/xe3lpd_dmc.bin" /lib/firmware/i915/

echo "--- Installing Cirrus speaker firmware ---"
mkdir -p /lib/firmware/cirrus
cp "$FWDIR"/cirrus/*17aa2352* /lib/firmware/cirrus/ 2>/dev/null || true

### 5. Install SOF audio firmware from sof-bin
echo ""
echo "--- Downloading sof-bin for SOF audio firmware ---"
SOF_VERSION=$(curl -s https://api.github.com/repos/thesofproject/sof-bin/releases/latest | grep tag_name | cut -d'"' -f4)
SOF_TARBALL="sof-bin-${SOF_VERSION#v}.tar.gz"
wget -q "https://github.com/thesofproject/sof-bin/releases/download/${SOF_VERSION}/${SOF_TARBALL}" \
    -O /tmp/sof-bin.tar.gz
tar -xzf /tmp/sof-bin.tar.gz -C /tmp

SOF_DIR=$(find /tmp -maxdepth 1 -name 'sof-bin-*' -type d | head -1)

echo "--- Installing SOF PTL firmware ---"
mkdir -p /lib/firmware/intel/sof-ipc4/ptl
cp "$SOF_DIR"/sof-ipc4/ptl/sof-ptl.ri /lib/firmware/intel/sof-ipc4/ptl/
cp "$SOF_DIR"/sof-ipc4/ptl/sof-ptl-openmodules.ri /lib/firmware/intel/sof-ipc4/ptl/

echo "--- Installing SOF topology files ---"
mkdir -p /lib/firmware/intel/sof-ipc4-tplg
cp "$SOF_DIR"/sof-ipc4-tplg/*.tplg /lib/firmware/intel/sof-ipc4-tplg/

### 6. Install additional topology files from Ubuntu's firmware-sof-signed
echo ""
echo "--- Downloading Ubuntu firmware-sof-signed for additional topology files ---"
UBUNTU_SOF_URL="http://archive.ubuntu.com/ubuntu/pool/main/f/firmware-sof/firmware-sof-signed_2025.12.2-1_all.deb"
wget -q "$UBUNTU_SOF_URL" -O /tmp/firmware-sof-ubuntu.deb
dpkg-deb -x /tmp/firmware-sof-ubuntu.deb /tmp/sof-ubuntu

echo "--- Installing SDCA and HDMI topology files ---"
cp /tmp/sof-ubuntu/usr/lib/firmware/intel/sof-ipc4-tplg/sof-sdca-*.tplg \
    /lib/firmware/intel/sof-ipc4-tplg/
cp /tmp/sof-ubuntu/usr/lib/firmware/intel/sof-ipc4-tplg/sof-hdmi-pcm5-id*.tplg \
    /lib/firmware/intel/sof-ipc4-tplg/


### 6b. Install UCM (Use Case Manager) config files for CS42L45
echo ""
echo "--- Downloading Ubuntu alsa-ucm-conf for CS42L45 UCM support ---"
UBUNTU_UCM_URL="http://archive.ubuntu.com/ubuntu/pool/main/a/alsa-ucm-conf/alsa-ucm-conf_1.2.15.3-1ubuntu1_all.deb"
wget -q "$UBUNTU_UCM_URL" -O /tmp/alsa-ucm-conf-ubuntu.deb
dpkg-deb -x /tmp/alsa-ucm-conf-ubuntu.deb /tmp/alsa-ucm-conf-ubuntu

echo "--- Installing CS42L45 UCM codec files ---"
cp -r /tmp/alsa-ucm-conf-ubuntu/usr/share/alsa/ucm2/codecs/cs42l45 /usr/share/alsa/ucm2/codecs/
cp -r /tmp/alsa-ucm-conf-ubuntu/usr/share/alsa/ucm2/codecs/cs42l45-dmic /usr/share/alsa/ucm2/codecs/
cp /tmp/alsa-ucm-conf-ubuntu/usr/share/alsa/ucm2/sof-soundwire/cs42l45.conf /usr/share/alsa/ucm2/sof-soundwire/
cp /tmp/alsa-ucm-conf-ubuntu/usr/share/alsa/ucm2/sof-soundwire/cs42l45-dmic.conf /usr/share/alsa/ucm2/sof-soundwire/

echo "--- Updating sof-soundwire UCM config ---"
cp /tmp/alsa-ucm-conf-ubuntu/usr/share/alsa/ucm2/conf.d/sof-soundwire/sof-soundwire.conf /usr/share/alsa/ucm2/conf.d/sof-soundwire/sof-soundwire.conf

### 7. Download and prepare kernel source for module building
echo ""
echo "--- Downloading kernel source ---"
cd /root
if [ ! -d "linux-$(uname -r | cut -d+ -f1)" ]; then
    # Add deb-src if not present
    if ! grep -q 'deb-src.*trixie-backports' /etc/apt/sources.list.d/*.list 2>/dev/null && \
       ! grep -q 'deb-src.*trixie-backports' /etc/apt/sources.list 2>/dev/null; then
        echo "deb-src http://deb.debian.org/debian trixie-backports main" \
            >> /etc/apt/sources.list.d/backports.list
        apt update
    fi
    apt source linux=$(uname -r | sed 's/+deb.*//;s/-amd64//')-1~bpo13+1 2>/dev/null || true
fi

KVER=$(uname -r | cut -d+ -f1)
KSRC="/root/linux-${KVER}"

if [ ! -d "$KSRC" ]; then
    echo "ERROR: Could not find kernel source at $KSRC"
    echo "Please run: apt source linux=$(uname -r | sed 's/+deb.*//;s/-amd64//')-1~bpo13+1"
    exit 1
fi

### 8. Build missing SDCA kernel modules
echo ""
echo "--- Building SDCA class kernel modules ---"
cd "$KSRC"

make -j$(nproc) -C /lib/modules/$(uname -r)/build M=$(pwd)/sound/soc/sdca \
    CONFIG_SND_SOC_SDCA_CLASS=m \
    CONFIG_SND_SOC_SDCA_CLASS_FUNCTION=m \
    modules

echo "--- Installing SDCA modules ---"
cp sound/soc/sdca/snd-soc-sdca-class.ko \
    /lib/modules/$(uname -r)/kernel/sound/soc/sdca/
cp sound/soc/sdca/snd-soc-sdca-class-function.ko \
    /lib/modules/$(uname -r)/kernel/sound/soc/sdca/

### 9. Update module dependencies and initramfs
echo ""
echo "--- Updating module dependencies and initramfs ---"
depmod -a
update-initramfs -u

echo ""
echo "=== Setup complete! ==="
echo "Please reboot to apply all changes."
echo ""
echo "After reboot, verify with:"
echo "  aplay -l                    # should show sof-soundwire"
echo "  ls /sys/class/backlight/    # should show backlight control"
echo "  speaker-test -c2 -t wav -D hw:0,2  # should play audio"
