#!/bin/bash
update_status=/var/cache/somerville/amd_driver_update_status
somerville_cache=/var/cache/somerville

notify-user(){
    [ $# == 0 ] && return
    local xuser_display_pairs=($(who | sed 's/[(|)]/ /g' | awk '{print $1 " " $5}' | grep ":"))
    for(( i=0; i < ${#xuser_display_pairs[@]}; i+=2));
    do
        XAUTHORITY=/home/${xuser_display_pairs[$i]}/.Xauthority DISPLAY=${xuser_display_pairs[$((i+1))]} notify-send -u critical "$1"
    done
    wall "$1"
}

handle_failure(){
    echo "update_failed $1" > $update_status
    notify-user "AMD driver updating failed!"
    exit
}
# check if user selected to update.
grep "need_install" $update_status || exit 0

mkdir -p $somerville_cache

amdgpu_type="amdgpu-pro"
dpkg -l | grep -e "libgl.*amdgpu-pro" > /dev/null || amdgpu_type="amdgpu"

amd_tarball=$(basename $(ls $somerville_cache/${amdgpu_type}*.xz))
amd_extracted_folder=${amd_tarball%.*.*}
[ -e $somerville_cache/$amd_tarball ] || handle_failure 1;

tar xf $somerville_cache/$amd_tarball -C $somerville_cache
cd $somerville_cache/$amd_extracted_folder

while [ 1 ];
do
    sleep 5
    fuser /var/lib/dpkg/lock || break
#    [ -z "$(pidof apt)" ] && [ -z "$(pidof apt-get)" ] && break
done

notify-user "** updating AMD driver in background, DO NOT reboot or shutdown machine **"
if [ "$amdgpu_type" == "amdgpu-pro" ]; then
    bash -c "yes|./amdgpu-pro-install && echo \"update_done\" > $update_status"
else
    bash -c "dpkg -i *.deb && echo \"update_done\" > $update_status"
fi

# failed case
grep update_done $update_status || handle_failure 2

cd ../
rm -rf $amd_extracted_folder $amd_tarball
systemctl disable oem-amd-gpu-updater.service
notify-user "AMD driver updated, you can reboot machine now. The new driver will be used after next boot."
