#!/usr/bin/env fish

function get_deb
	###
	# required set global vars:
	# url_base - apt repo base url
	# versions - output of (wget -qO- $url_base/path/to/Packages.gz | gzip -d | grep "^Filename:" | cut -d' ' -f2 | sort -u | grep -e '-[0-9]' | string split ' ')
	# package_set - list of package names taken from that apt repo
	###
	
	set -l package_versioned_set
	
	for package in $package_set
		set -l package_versioned
		
		for _version in $versions
			set -a package_versioned $(echo $_version | grep -e $package\-[0-9\.-]\*_)
		end
		
		set -a package_versioned_set $package_versioned[-1]
	end
	
	set -l urls
	for package in $package_versioned_set
		set -a urls $url_base/$package
	end
	
	echo $urls
end

function update_urls
	for package_dir in $package_dirs
		set -g package_set (cat $package_dir/deb_names)
		
		set -g deb_urls (get_deb)
		
		# construct the SRC_URI string
		set -l _uuid (uuidgen)
		echo 'SRC_URI="\\' > /tmp/$_uuid
		for deb_url in (echo $deb_urls | string split ' ')
			printf '\t%s\\\n' $deb_url >> /tmp/$_uuid
		end
		echo '"' >> /tmp/$_uuid
		
		# replace the block
		set ebuild_file "$package_dir/$(echo $package_dir | string split '/')[-1]-9999.ebuild"
		if ! test -f "$FILE"
			echo "Can't update missing file:"
			echo "$ebuild_file"
			echo "#======="
			sed -e 's/\\\n/\n/g' /tmp/$_uuid | string replace '\\' ''
			echo "#======="
			break
		end
		
		local overwrite="n"
		echo "Overwrite SRC_URI in $ebuild_file ?"
		echo "[y/n]"
		while true
			read -f overwrite
			[[ "$overwrite" == y* || "$overwrite" == n* ]] && echo "$overwrite" && break || echo "unrecognized input"
		end
		echo $overwrite
		if [[ "$overwrite" == y* ]]
			break
			sed '/^SRC_URI="/,/^"/c\\'"$(cat /tmp/$_uuid)" -i "$ebuild_file"
			rm /tmp/$_uuid
			
			# update manifests
			cd $package_dirs
			pkgdev manifest
		else
			echo "fuck"
		end
	end
end

###

# script dir
set -l DIR (cd (dirname (status -f)); and pwd)

# folders to process
set -g package_dirs (find $DIR -name 'deb_names' | string replace '/deb_names' '')

set -g url_base "https://apt.repos.intel.com/oneapi"
set -g versions (wget -qO- $url_base/dists/all/main/binary-amd64/Packages.gz | gzip -d | grep "^Filename:" | cut -d' ' -f2 | sort -u | grep -e '-[0-9]*.[0-9]-[0-9]*.[0-9].[0-9]*' | string split ' ')

switch $argv[1]
  case 'update'
    echo Updating:
    echo $package_dirs | string split ' '
    update_urls && return 0 || return 1
  case 'fetch'
    echo $versions | string split ' ' && return 0
  case ''
    #help
    return 0
  case  '*'
    echo Unsupported operation
    return 1
end
