#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2021"
app="$(basename $0)"
msgid="The Starbuntu application
<i>\$app</i>
was written by"
info="$(gettext "$msgid" | (export PATH `envsubst --variables "$msgid"`; envsubst "$msgid"))"

yad --center --fixed --title="$title" --window-icon="info" --image="info" --borders=20 --text="$info"$'\n'$'\n'"$author"$'\n'"$mail"$'\n'$'\n'"$year"$'\n' --text-align=center --selectable-labels --button="OK" &
wunwa "$title" > /dev/null; xdotool key Home key Down
}

if [ "$1" = "info" ]; then Info; exit 0; fi

expose_url="$@"
type="application/x-mswinurl"
lang_dir=$"C"
if [ "$(xdg-mime query filetype "$expose_url")" != "$type" ]; then
    title=$"Error"
    url="${expose_url//\&/\&amp\;}"
    text=$"	'$url'&#10;	isn't a file of the type&#10;	'$type'!"
    button=$"Help"
    yad --center --title="$title" --window-icon=$HOME/.icons/webbrowser.png --image="dialog-warning" --text="$text" --borders=20 --button=$button:"yelp /usr/share/help/$lang_dir/Starbuntu/starbuntu-apps-details.page#expose-url" --button="OK":0
    exit 1
fi

expose_url=$(cat "$expose_url" | grep "URL=")
expose_url=${expose_url#*URL=}
type="${expose_url%%:*}"
[ "$type" = "$expose_url" ] && type="file"
type="x-scheme-handler/$type"
icon=""; ask_symbol=true; web_addr=false
url_name="${expose_url#*//}"
[ "${url_name: -1}" = "/" ] && url_name="${url_name::-1}"
url_name="$(echo "$url_name" | sed 's/^www.//')"
[ "$url_name" != "$expose_url" ] && [ "${url_name::1}" != "/" ] && url_name="${url_name%%/*}" && web_addr=true
if $web_addr; then
    exist_png=true
    link="$(curl -Ls "${expose_url%%$url_name*}$url_name/" | grep -E "<link rel=.*icon\"" | grep -E "(\.ico|\.png)" | grep -v "apple" | head -1)"
    [ -z "$link" ] && link="$(curl -Ls "$expose_url" | grep -E "<link rel=.*icon\"" | grep -E "(\.ico|\.png)" | grep -v "apple" | head -1)"
    link="$(echo "$link" | sed 's/<link //; s/\/>//; s/>//')"
    eval "$link"
    [[ ! "$href" =~ \.png$ ]] && exist_png=false
    if [ -n "$href" ]; then
	[[ "$href" =~ ^\./ ]] && href="${href:1}"
	[ "${href::4}" != "http" ] && href="${expose_url%%$url_name*}$url_name$href"
	ico_name=$HOME/Urls/favicons/$url_name.${href##*.}
	curl --no-progress-meter --user-agent Chrome/117.0.0.0 $href -o $ico_name
	if [ $? -eq 0 ]; then
	    icon="${ico_name%.*}.png"
	    if ! $exist_png; then
		convert -thumbnail 48x48 -alpha on -background none -flatten "$ico_name" "$icon"
		rm "$ico_name"
	    fi
	    [ -e "$icon" ] && ask_symbol=false
	fi
    fi
fi

title=$"Expose URL"
text=$"&#10;<b>Please select an adequate icon for the URL '$url_name...'!</b>&#10;"
cancel=$"Cancel"

if $ask_symbol; then
    icon="$(yad --title="$title" --center --width=900 --height=700 --text="$text" --text-align=center --window-icon=$HOME/.icons/webbrowser.png --file --filename=$HOME/.icons --file-filter $"Graphic Files "" | *.jpg *.jpeg *.png *.JPG *.JPEG *.PNG" --add-preview --button="$cancel":1 --button="Info":"$0 info" --button="OK":0)"
fi

[ -z "$icon" ] && icon="$HOME/.icons/webbrowser.png"

title2="$(echo $"Set Application")"
ask="$(echo $"Which app shall open the URL? (empty: default app)")"
cancel=$"Cancel"

IFS=$'\n'
cd /usr/share/applications
app_mime=$(xdg-mime query default $type)
app_list=($(grep -l $type * | grep -v mimeinfo.cache | grep -v defaults.list))
app_list=($(sed 's/\.desktop//g' <<< "${app_list[*]/$app_mime}"))
app_list=( `for i in ${app_list[@]}; do echo $i; done | sort -u` )
app_list=(${app_mime%.*} ${app_list[@]})

app=`yad --center --title="$title2" --window-icon=$HOME/.icons/webbrowser.png --fixed --borders=10 --list --editable --no-headers --column=Apps ${app_list[@]} --text="<b>$ask</b>" --entry --button="$cancel":1 --button="Info":"$0 info" --button="OK":0`

if [ -n "$app" ]; then
    if [[ ! "$app" =~ ^x\ |^exec-desktop|.desktop$ ]]; then
	cd $HOME/.local/share/applications
	found="$(ls * | grep -iE "^(^$app|$app|${app//-}).desktop" | head -1)"
	[ -n "$found" ] && app="x $found"
	if [[ ! "$app" =~ ^x\ |^exec-desktop|.desktop$ ]]; then
	    cd /usr/share/applications
	    found="$(ls * | grep -iE "(^$app|$app|${app//-}).desktop" | head -1)"
	    [ -n "$found" ] && app="x $found"
	fi
    fi
    app="$app "
fi

f_menu="$HOME/.config/gtk-3.0/links.lst"
id_fs=($(grep -n '}‖' $f_menu))
if [ -n "$id_fs" ]; then
    for ((i=0; i<${#id_fs[*]}; i++)); do
      nr="${id_fs[$i]%%:*}"
      id_fs[$i]="${id_fs[$i]#*:}":$nr
    done
    idf=($(for ((i=0; i<${#id_fs[*]}; i++)); do
      label="${id_fs[$i]##*‖}"
      detail="${id_fs[$i]%‖*}"
      detail="${detail##*‖}"
      [ "${label::1}" = "{" ] && line="${label%\}*}}!$detail!‖$label" || line="$detail!!‖$label"
      echo "$line"
    done | sort -t'!' -k 1,1 -k 2,2 --ignore-case))
    main_id="$(echo $"Main Level:0")"
    idf=($main_id ${idf[@]//\!/})
    h=${#idf[@]}; h=$(((h+11)*20))

    IFS='¦'
    id_f=($(for ((i=0; i<${#idf[*]}; i++)); do
      idf[$i]="${idf[$i]##*:}¦${idf[$i]##*‖}"
      echo "${idf[$i]%:*}¦"
    done))
    id_f=($(echo "${id_f[*]}" | sed 's/{[^}]*}/    /g'))

    title="$(echo $"Select Identifier")"
    text="$(echo $"Select the place of the URL:")"
    oktext="$(echo $"Integrate URL there")"
    cancel=$"Cancel"

    name=`yad --center --title="$title" --window-icon=format-indent-less-rtl --width=350 --height=$h --borders=20 --text="$text"$'\n' --list --no-headers --column="Idf":HD --column="Identifiers" ${id_f[@]} --button="$cancel":1 --button="Info":"$0 info" --button="OK!!""$oktext":0`
    exit_code=$?
    [ $exit_code -eq 1 ] && exit $exit_code

    IFS=$'\n'
    n_id=${name%%\|*}
    label="${name#*▶ }"; label="${label::-1}:$n_id$"; label="${label/$'\n'/}"
    id="$(echo "${idf[*]}" | grep -e "$label")"
    id="${id%‖*}"
else
    id=""
fi

contents="$(curl --no-progress-meter --user-agent Chrome/117.0.0.0 "$expose_url")"
[ -z "$contents" ] && contents="$(curl --no-progress-meter "$expose_url")"
contents="$(tr -d '\n' <<< $contents)"
label="$(echo "$contents" | grep -o "<title>[^>]*>" | head -n 1)"
label="$(echo "$label" | sed -E 's/<[^>]*>([^<]*)<.*/\1/')"
label="$(echo "$label" | xargs)"
if [ -z "$label" ]; then
    [ "${expose_url: -1}" = "/" ] && expose_url="${expose_url::-1}"
    label=${expose_url##*/}
    if [ "${label::1}" = "?" ] || [[ "$label" =~ ^index|^default|^start ]]; then
	label="$url_name"
	[[ "$label" =~ index|default|start ]] && label="${label%/*}"
    fi
    if [[ "$label" =~ index|default|start ]]; then
	label=$(basename "$(dirname "$expose_url")")
    else
	label=${label%\?*}
	[ "${label::7}" != "mailto:" ] && label=${label%.*}
    fi
    label="$(sed 's/-/ /g; s/_/ /g' <<< $label)"
fi

title=$"Set URL Label"
msg=$"&#9;<b>The URL label&#10;&#9;'$label'&#10;&#9;is to be added to the exposed URLs.&#10;&#9;Edit URL label:</b>&#10;"
re1=$"Yes"; re2=$"No"
label=`yad --center --title="$title" --window-icon="$HOME/.icons/webbrowser.png" --fixed --borders=40 --image="dialog-question" --text="$msg" --entry-text="$label" --entry --button="Info":"$0 info" --button="OK":0`

echo "$icon‖$app$expose_url‖$id$label" >> $HOME/.config/gtk-3.0/links.lst
exit 0
