#!/bin/sh
set -eu

target=${1:?usage: install-linux-build-dependencies.sh arm64|x64}

install_packages() {
    sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "$@"
}

case "$target" in
    arm64)
        sudo apt-get update
        install_packages \
            build-essential \
            cmake \
            libgtk-3-dev \
            libwebkit2gtk-4.1-dev \
            libxdo-dev \
            pkg-config
        ;;
    x64)
        if [ "$(dpkg --print-architecture)" != "arm64" ]; then
            echo "the x64 release build expects an arm64 Ubuntu runner" >&2
            exit 1
        fi
        if [ ! -r /etc/os-release ]; then
            echo "cannot determine the Ubuntu release" >&2
            exit 1
        fi
        . /etc/os-release
        if [ "${ID:-}" != "ubuntu" ] || [ -z "${VERSION_CODENAME:-}" ]; then
            echo "the x64 release build requires an Ubuntu runner" >&2
            exit 1
        fi

        sudo dpkg --add-architecture amd64
        {
            printf '%s\n' \
                'Types: deb' \
                'URIs: http://archive.ubuntu.com/ubuntu' \
                "Suites: $VERSION_CODENAME ${VERSION_CODENAME}-updates" \
                'Components: main universe restricted multiverse' \
                'Architectures: amd64' \
                'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg' \
                '' \
                'Types: deb' \
                'URIs: http://security.ubuntu.com/ubuntu' \
                "Suites: ${VERSION_CODENAME}-security" \
                'Components: main universe restricted multiverse' \
                'Architectures: amd64' \
                'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg'
        } | sudo tee /etc/apt/sources.list.d/ruds-amd64.sources >/dev/null
        sudo apt-get update
        install_packages \
            build-essential \
            cmake \
            gcc-x86-64-linux-gnu \
            g++-x86-64-linux-gnu \
            libgtk-3-dev:amd64 \
            libwebkit2gtk-4.1-dev:amd64 \
            libxdo-dev:amd64 \
            pkg-config
        ;;
    *)
        echo "unsupported Linux build target: $target" >&2
        exit 1
        ;;
esac
