#!/usr/bin/env fish

set aur_package_list \
    nordvpn-bin \
    touchegg-git

set package_list \
    kcm-wacomtablet \
    libratbag

function log
    echo >&2 $argv
end

function warn
    echo >&2 (set_color yellow)"WARNING: $argv"(set_color normal)
end

function die
    echo >&2 (set_color red)"FATAL: $argv"(set_color normal)
    exit 1
end

function install_yay
    log "Installing yay-bin..."
    # first install yay-bin to get AUR packages
    sudo pacman -S --noconfirm --needed git base-devel
    git clone https://aur.archlinux.org/yay-bin.git
    pushd yay-bin
    makepkg -si --noconfirm
    yay -Syu --noconfirm
    popd
end

function build_packages
    log "Downloading + building packages..."
    for pkg in $aur_package_list
        yay -G --noconfirm $pkg
        pushd $pkg
        if ! makepkg -s --noconfirm
            warn "failed to build $pkg"
        end
        popd
    end
end

function build_smiusbdisplay_driver
    yay -S --noconfirm linux-neptune-headers

    git clone https://github.com/ian-h-chamberlain/steamos-smiusbdisplay-drivers.git

    # https://github.com/ian-h-chamberlain/steamos-smiusbdisplay-drivers/blob/main/README.md#build
    pushd steamos-smiusbdisplay-drivers/evdi-steamos-dkms
    makepkg -si --noconfirm

    set kernel (uname -r)
    set evdi_version (pacman -Q evdi-steamos-dkms | cut -d' ' -f2 | cut -d- -f1)

    sudo dkms build evdi/$evdi_version -k $kernel

    # Export dkms module somewhere the host can access it
    sudo dkms mktarball evdi/$evdi_version -k $kernel
    cp /var/lib/dkms/evdi/$evdi_version/tarball/*.tar.gz ..

    # Build the SMI usb driver itself
    cd ../smiusbdisplay-driver-bin
    if ! makepkg -s --noconfirm
        warn "failed to build SMI USB display driver. Maybe it's already installed?"
    end

    popd
end

function install_packages
    log "Disabling read-only filesystem..."
    # TODO: this is broken in 3.4.10 it seems. This workaround only works on btrfs
    # sudo steamos-readonly disable
    sudo btrfs property set / ro false
    or die "Failed to disable read-only filesystem! Unable to continue"

    log "Installing AUR packages..."
    # NOTE: we use --overwrite since there might be some leftover /var/, /etc/
    # type files from previous installations. This might require some additional
    # login / configuration after reinstalling but is probably safer in the long run

    cd $build_dir
    for pkg in $aur_package_list
        pushd $pkg
        sudo pacman -U --overwrite '*' --noconfirm *.tar.zst
        or warn "failed to install $pkg!"
        popd
    end

    log "Installing other packages..."
    for pkg in $package_list
        sudo pacman -S --overwrite '*' --noconfirm $pkg
        or warn "failed to install $pkg!"
    end

    log "Installing SMI USB display driver..."
    # https://github.com/ian-h-chamberlain/steamos-smiusbdisplay-drivers/blob/main/README.md#install
    pushd steamos-smiusbdisplay-drivers
    sudo pacman -S --noconfirm dkms

    set kernel (uname -r)
    set evdi_version (printf *.tar.gz | cut -d- -f2)

    # Load and install the previously built dkms archive
    sudo dkms ldtarball *.tar.gz
    sudo dkms install evdi/$evdi_version -k $kernel

    # Install the built SMI usb driver
    pushd evdi-steamos-dkms
    sudo pacman -U --overwrite '*' --noconfirm *.tar.zst
    or warn "failed to install evdi!"
    popd

    pushd smiusbdisplay-driver-bin
    sudo pacman -U --overwrite '*' --noconfirm *.tar.zst
    or warn "failed to install SMI USB display driver!"
    popd

    popd

    log "Re-enabling read-only filesystem..."
    sudo steamos-readonly enable
end


## Main script
if test -f /run/.containerenv
    if source (string replace -r '^.+$' 'export CONTAINER_$0' </run/.containerenv | psub)
    and not string match --quiet 'distrobox-*' $CONTAINER_name
        exec distrobox-host-exec (status --current-filename) $argv
    end

    set build_dir $argv[1]
    cd $build_dir
    install_yay
    or die "Failed to install `yay` for package build"
    build_packages
    or die "Failed to build requested AUR packages"
    build_smiusbdisplay_driver
    or die "Failed to build SMI USB display driver"
else
    set build_dir (mktemp -d)
    trap "rm -rf $build_dir" EXIT

    # download and build packages inside a fresh HoloISO container
    distrobox ephemeral \
        --image ghcr.io/steamdeckhomebrew/holo-base:latest \
        --pull \
        -- (status --current-filename) $build_dir
    or die "Failed build, unable to continue installation"

    set response (read --prompt-str "Install packages? [Y/n]: ")
    if string match --quiet --regex '^[yY]?$' -- "$response"
        if install_packages
            log "Done! Reboot for installation to complete."
        else
            warn "Failed to install some packages!"
        end
    else
        log "Skipping package installation. Nothing left to do."
    end
end
