#!/bin/bash
# simple bash script to check if update is available by comparing local version and remote version

# Local Paths
local_dir="$HOME/.config/hypr"
iDIR="$HOME/.config/swaync/images/ja.png"
local_version=$(ls $local_dir/v* 2>/dev/null | sort -V | tail -n 1 | sed 's/.*v\(.*\)/\1/')
hyprland_dotfiles_DIR="$HOME/nixos-dots"

# exit if cannot find local version
if [ -z "$local_version" ]; then
  notify-send -i $iDIR "ERROR "!?!?!!"" "Unable to find nixos-dots version . exiting.... "
  exit 1
fi

# git repo - nixos-dots
branch="master"
remote_url="https://g.r-io.lu/shynd/nixos-dots/src/$branch/config/hypr/"

# Fetch the version from git repo URL - nixos-dots
remote_version=$(curl -s $remote_url | grep -o 'v[0-9]\+\.[0-9]\+\.[0-9]\+' | sort -V | tail -n 1 | sed 's/v//')

# Cant find  GitHub URL - nixos-dots version
if [ -z "$remote_version" ]; then
  exit 1
fi

# Comparing local and remote versions
if [ "$(echo -e "$remote_version\n$local_version" | sort -V | head -n 1)" = "$remote_version" ]; then
   notify-send -i $iDIR "nixos-dots:" "No update available"
  exit 0
else
  # update available
  notify_cmd_base="notify-send -t 10000 -A action1=Update -A action2=NO -h string:x-canonical-private-synchronous:shot-notify"
  notify_cmd_shot="${notify_cmd_base} -i $iDIR"

  response=$($notify_cmd_shot "nixos-dots:" "Update available! Update now?")

  case "$response" in
    "action1")  
      if [ -d $hyprland_dotfiles_DIR ]; then
      	if ! command -v kitty &> /dev/null; then
  			notify-send -i $iDIR "Need Kitty:" "Kitty terminal not found. Please install Kitty terminal."
  			exit 1
		fi
        kitty -e bash -c "
          cd $hyprland_dotfiles_DIR &&
          git stash &&
          git pull &&
          ./copy.sh &&
		  notify-send -u critical -i $iDIR 'Update Completed:' 'Kindly log out and relogin to take effect'
        "
	
      else
         if ! command -v kitty &> /dev/null; then
  		  	notify-send -i $iDIR "Need Kitty:" "Kitty terminal not found. Please install Kitty terminal."
  			exit 1
		fi
        kitty -e bash -c "
          git clone --depth=1 https://g.r-io.lu/shynd/nixos-dots.git $hyprland_dotfiles_DIR &&
          cd $hyprland_dotfiles_DIR &&
          chmod +x copy.sh &&
          ./copy.sh &&
		  notify-send -u critical -i $iDIR 'Update Completed:' 'Kindly log out and relogin to take effect'
        "
      fi
      ;;
    "action2")
      exit 0
      ;;
  esac
fi
