#!/bin/bash

Info () {
title="Info"
author="Peter Starfinger"
mail="E-Mail: info@die-starfingers.de"
year="2020"
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 --title="$title" --window-icon="info" --image="info" --borders=20 --text="$info"$'\n'$'\n'"$author"$'\n'"$mail"$'\n'$'\n'"$year" --text-align=center --selectable-labels --button="OK" &
wunwa "$title"; xdotool key Home key Down
}

write () {
    rm $or_file
    for ((k=0; k<$l_orrc; k++)); do
	echo "${orrc[$k]#*‖}" >> $or_file
    done
}

edit () {
    title=$"Edit Entry No."" $((no+1))"
    device=$"Block Devices"
    iso=$"ISO Files"
    name=$"<Address Label for ftp,sftp,ssh,webdav>"
    nome=$"Label&#58; "
    aim=$"Address: "
    utente=$"User:"
    passw=$"Password:"
    button1=$"New"
    loop=true; new=false
    etikett="${label[$no]}"
    [ "${type[$no]}" = "iso" ] && addr[$no]="${addr[$no]#*://}" 
    [ "${type[$no]}" != "iso" ] && adresse="${addr[$no]}" || adresse="iso://${addr[$no]}"
    benutzer="${usr[$no]}"
    passwort="${pass[$no]}"
    del="--button=Del:3"
    neu="--button=$button1:2"
    while $loop; do
	output=`yad --center --title="$title" --width=600 --height=200 --window-icon=$HOME/.icons/remote.png --borders=10 --form --separator="‖" --field="$nome":CBE "$etikett!$device!$iso!$name" --field="$aim":CBE "$adresse!iso://...!ftp://...!sftp://...!sshfs://...!ssh://...!https://..." --field="$utente" "$benutzer" --field="$passw" "$passwort" --button=$"Main Menu":1 $del $neu --button="$button2":"yelp /usr/share/help/$lang_dir/Starbuntu/starbuntu-apps-details.page#open-remote" --button="Info":"$0 info" --button="OK":0`
	e_code=$?
	if [ $e_code -eq 2 ]; then
	    etikett=""; adresse=""; benutzer=""; passwort=""; del=""; neu=""; new=true
	else
	    loop=false
	    [ $e_code -eq 1 ] && new=false
	fi
    done
    [ $e_code -ne 1 ] && changed=true
    $new && e_code=2
    if [ $e_code -eq 3 ]; then
	for ((k=$no; k<$l_orrc; k++)); do
	    label[$k]=${label[$((k+1))]}
	    addr[$k]=${addr[$((k+1))]}
	    usr[$k]=${usr[$((k+1))]}
	    pass[$k]=${pass[$((k+1))]}
	    type[$k]=${type[$((k+1))]}
	    orrc[$k]=${orrc[$((k+1))]}
	done
	unset nr[$((l_orrc-1))]; unset label[$((l_orrc-1))]; unset addr[$((l_orrc-1))]; unset usr[$((l_orrc-1))]; unset pass[$((l_orrc-1))]; unset type[$((l_orrc-1))]; unset entry[$((l_orrc-1))]
	((l_orrc--))
    fi
    if [ $e_code -eq 2 ]; then
	for ((k=$l_orrc; k>$no; k--)); do
	    label[$k]=${label[$((k-1))]}
	    addr[$k]=${addr[$((k-1))]}
	    usr[$k]=${usr[$((k-1))]}
	    pass[$k]=${pass[$((k-1))]}
	    type[$k]=${type[$((k-1))]}
	    orrc[$k]=${orrc[$((k-1))]}
	done
	nr[$l_orrc]=$l_orrc; label[$no]=""; addr[$no]=""; usr[$no]=""; pass[$no]=""; type[$no]=""; entry[$no]=""
	((l_orrc++))
    fi
    if [ $e_code -eq 0 ] || [ $e_code -eq 2 ]; then
	label[$no]="${output%%‖*}"; output="${output#*‖}"
	addr[$no]="${output%%‖*}"; output="${output#*‖}"
	usr[$no]="${output%%‖*}"; output="${output#*‖}"
	pass[$no]="${output%%‖*}"; output="${output#*‖}"
	dest="${addr[$no]}"
	[ -z "${addr[$no]}" ] && dest="" || dest="‖dest=${addr[$no]}"
	[ -z "${usr[$no]}" ] && benutzer="" || benutzer="‖user=${usr[$no]}"
	[ -z "${pass[$no]}" ] && passw="" || passw="‖passwd=${pass[$no]}"
	orrc[$no]="nr[$no]=$no‖name=${label[$no]}$dest$benutzer$passw"
	sort="${dest%://*}"; sort="${sort:6}"
	case "$sort" in
	    iso)	type[$no]="iso"; addr[$no]="${addr[$no]:6}" ;;
	    ftp)	type[$no]="ftp"  ;;
	    sftp)	type[$no]="sftp" ;;
	    sshfs)	type[$k]="sshfs" ;;
	    ssh)	type[$no]="ssh"  ;;
	    http|https)	type[$no]="dav"  ;;
	    *)		type[$no]="dev"  ;;
	esac
    fi
    remtype=""; go_on=false
}

body()
{
go_on=true
IFS='‖'

title=$"Remote Sources"
button2=$"Help"
lang_dir=$"C"
for ((k=0; k<$l_orrc; k++)); do entry[$k]="${nr[$k]}‖${label[$k]}"; done
remote=`yad --center --title="$title" --height=$((l_orrc*24+72)) --width=250 --borders=10 --window-icon=$HOME/.icons/remote.png --button=$"Quit":1 --button="Edit":2 --button="$button2":"yelp /usr/share/help/$lang_dir/Starbuntu/starbuntu-apps-details.page#open-remote" --button="Info":"$0 info" --button="OK":0 --list --separator="‖" --list-separator="‖" --no-headers --column=Nr:HD --column=Remotes ${entry[@]} --search-column=2`
error=$?
button=$"Main Menu"
if [ $error -eq 1 ]; then remtype=""; go_on=false; leave=true; fi

if [ -n "$remote" ]; then
    remote=${remote::-1}
    no=${remote%%‖*}
    remtype=${type[$no]}
else
    remtype=""; go_on=false; leave=true
fi

if [ $error -eq 2 ]; then edit; fi

case "$remtype" in
    dev) devs=(); i=0; p_known=false;
      own="$(lsblk -o 'KNAME,TYPE,RM' | grep disk | grep 0 | awk '{ print $1 }')"
      if ! $(sudoer $USER); then nodisplay="$own"; else nodisplay="ßßß"; fi
      while read line; do
	if ! $p_known; then
	  p_knm=0
	  p_lbl=$(echo "$line" | grep -b -o LABEL); p_lbl=${p_lbl%%:*}
	  p_mpt=$(echo "$line" | grep -b -o MOUNTPOINT); p_mpt=${p_mpt%%:*}
	  p_typ=$(echo "$line" | grep -b -o "TYPE "); p_typ=${p_typ%%:*}
	  p_fst=$(echo "$line" | grep -b -o FSTYPE); p_fst=${p_fst%%:*}
	  p_known=true
	fi
	knm=${line:0:$p_lbl}
	lbl=${line:$p_lbl:(($p_mpt-$p_lbl))}
	mpt=${line:$p_mpt:(($p_typ-$p_mpt))}
	typ=${line:$p_typ:(($p_fst-$p_typ))}
	fst=${line:$p_fst}
        if ([ "$typ" = "part " ] && [[ ! "$fst" =~ "swap" ]] && [[ ! "$mpt" =~ "/ " ]]) || ([[ "$typ" =~ "rom" ]] && [ -n "$(echo $lbl)" ]); then
	  devs[$i]="$knm$lbl"
          (( i++ ))
        fi
      done < <(lsblk -o KNAME,LABEL,MOUNTPOINT,TYPE,FSTYPE | grep -v "$nodisplay")

      len=${#devs[@]}
      h=$((60+25*$len))
      remote_url=`yad --center --title=${remote##*‖} --height=$h --width=24 --borders=10 --window-icon=$HOME/.icons/remote.png --button="$button":1 --button="OK":0 --list --separator="‖" --list-separator="‖" --no-headers --column=Devices ${devs[@]}`
      remote_url=${remote_url:0:$p_lbl}
      remote_url="${remote_url// /}"

      if [ -z "$remote_url" ]; then
	go_on=false
	if [ "$button" = $"Quit" ]; then leave=true; fi
      fi ;;
    iso) iso=(); i=0
      iso_path=${addr[$no]}
      if [ ! -d "$iso_path" ]; then
	iso_path=""
	drv=$(lsblk -o  KNAME,LABEL | grep ${addr[$no]/\/dev\//})
	if [ -z "$drv" ]; then
	  yad --center --fixed --title=$"Error" --window-icon="dialog-warning" --image="dialog-warning" --borders=20 --button="OK":0 --text=$'\n'"$(echo $"This device doesn't exist!")" # '
          go_on=false
	fi
      fi
      if $go_on; then
        if [ -z "$iso_path" ]; then
	  drv=${drv:0:4}
	  mp=$(gio mount -d "/dev/$drv" 2>&1)
	  if [ $? -gt 0 ] && [[ ! "$mp" =~ "already mounted" ]]; then
	    [ $LANGUAGE != "en" ] && [ $(trans -b -identify "$mp") = "en" ] && mp="$(trans -b en:$LANGUAGE "$mp")"
	    yad --center --fixed --title=$"Error" --window-icon="dialog-warning" --image="dialog-warning" --borders=20 --button="OK":0 --text=$'\n'"$mp"
	    go_on=false
	  else
	    iso_path="/media/$USER/${addr[$no]}"
	  fi
	fi
	if $go_on; then
	  while read line; do
	    [ ${line::3} != "ls:" ] && name="${line##*\/}" && iso[$i]="$name" && (( i++ ))
	  done < <(ls -l $iso_path/*.iso $iso_path/*.img)
	  if [ "$i" = "0" ]; then
	    yad --center --fixed --title=$"Error" --window-icon="dialog-warning" --image="dialog-warning" --borders=20 --button="OK":0 --text=$'\n'"$(echo $"No ISO or IMG files found!")"
	    gio mount -u -f "$iso_path"; go_on=false
	  fi
	fi
      fi
      if $go_on; then
          len=${#iso[@]}
          h=$((55+25*$len))
          iso_sel=`yad --center --title="${label[$no]}" --height=$h --width=300 --borders=10 --window-icon=$HOME/.icons/remote.png --button=$"Main Menu":1 --button="OK":0 --list --separator="‖" --no-headers --column=Images ${iso[@]}`
          if [ -n "$iso_sel" ]; then
	    iso_sel=${iso_sel::-1}
	    remote_url="$iso_path/$iso_sel"
	  else
            gio mount -u -f "$iso_path"; go_on=false
	  fi
      fi ;;
    dav|ftp|sftp|ssh*) local_net="192.168."
	 if [[ "${addr[$no]}" =~ "$local_net" ]]; then
	     name="${label[$no]}"
	     ip_addr=$(ip neigh | awk '{ print $1 }' | xargs -n1 host | grep "$name")
	     if [ -n "$ip_addr" ]; then
		ip_addr="${ip_addr%%.168*}"
		ip_addr="${ip_addr: -1}.${ip_addr%.*}"
		addr_pre="${addr[$no]%$local_net*}"
		addr_post="${addr[$no]##*:}"
		addr[$no]="$addr_pre$local_net$ip_addr:$addr_post"
	     fi
	 fi
	 remote_url="${addr[$no]}"
	 remote_url="$(echo "$remote_url" | sed 's/sshfs/ssh/; s/sftp/ssh/')"
	 if [[ "$remtype" =~ s?ftp|ssh ]] && [[ "${addr[$no]}" =~ "192.168." ]]; then
	   gw_ip=`route -n | grep 'UG[ \t]' | awk '{print $2}'`
	   [ -z "$(grep $gw_ip$ <<< "${addr[$no]}")" ] && remote_url=`yad --center --title="Edit" --height=100 --width=400 --borders=10 --window-icon=$HOME/.icons/remote.png --button=$"Main Menu":1 --button="OK":0 --entry --entry-text="$remote_url"` # "
	   [ -z "$remote_url" ] && go_on=false
	   if $go_on; then
		ip="${remote_url#*://}"; ip="${ip%:*}"; ip="${ip%%/*}"
		hostname="$(nslookup "$ip" | grep 'name =' | head -1)"
		if [ -n "$hostname" ]; then
		    hostname="${hostname#*= }"
	  	    hostname="${hostname%.*}"
		    remote_url="${remote_url/$ip/$hostname}"
		fi
	   fi
	 fi  ;;
esac

if $go_on; then
    if [[ -n "$remote" ]]; then
      if [[ "$remtype" =~ dav|s?ftp|ssh ]]; then
	if [ -n "${pass[$no]}" ]; then
	  org=""; prl=${pass[$no]}; coded=true
	  for ((i=0; i<$((${#prl}/2)); i++)); do
	    diff=$(echo ${prl:$((2*i)):2} ${DSTR:$((2*i)):2} | dc -e '16o16i?-p' 2>&1)
	    if [ ${#diff} -gt 2 ]; then
	      coded=false; org=$prl; break
	    else
	      org=$org$diff
	    fi
	  done
	  if $coded; then
	    org=$(echo $org | xxd -r -p)
	  else
	    root=""; sum=""
	    for ((i=0;i<${#prl};i++));do root=$root$(printf %02X \'"${prl:$i:1}");done
	    for ((i=0;i<${#prl};i++));do sum=$sum$(echo ${root:$((2*i)):2} ${DSTR:$((2*i)):2} | dc -e '16o16i?+p'); done
	    orrc[$no]=${orrc[$no]/passwd=$org/passwd=$sum}
	    pass[$no]=$sum
	    mv $HOME/.config/gtk-3.0/orrc $HOME/.config/gtk-3.0/orrc.bak
	    for ((k=0; k<l_orrc; k++)); do echo "${orrc[$k]#*‖}" >> $HOME/.config/gtk-3.0/orrc; done
	  fi
	  mount_point="$(echo "$remote_url" | sed 's/:\/\//-/g')"
	  mount_point="$(echo "$mount_point" | sed 's/:[0-9]*//')"
	  mount_point="$(echo "$mount_point" | sed 's/\//-/g')"
	  mount_point="/media/$USER/$mount_point"
	  case "$remtype" in
	    dav)	msg=$(udevil mount $remote_url 2>&1 <<< "${usr[$no]}"$'\n'"$org") ;;
	    ftp)	remote_url="${remote_url/:\/\//:\/\/${usr[$no]}:$org@}"
	        	msg=$(udevil mount $remote_url 2>&1) ;;
	    sftp|sshfs) remote_url="${remote_url#*://}"
			msg=$(udevil mount -t sshfs -o password_stdin ${usr[$no]}@$remote_url 2>&1 <<< "$org") ;;
	    ssh) remote_url="${remote_url/:\/\//:\/\/${usr[$no]}@}"
	         msg=$(udevil mount -o password_stdin $remote_url 2>&1 <<< "$org") ;;
	  esac
	  if [ $? -gt 0 ]; then
		[ $LANGUAGE != "en" ] && [ $(trans -b -identify "$msg") = "en" ] && msg="$(trans -b en:$LANGUAGE "$msg")"
		yad --center --fixed --title=$"Error" --window-icon="dialog-warning" --image="dialog-warning" --borders=20 --button="OK":0 --text=$'\n'"$msg" && go_on=false && leave=true
	  fi
	else
	  udevil mount $remote_url
	fi
	sleep 1.5
      else
	automount "$remote_url"
	sleep 2
	if [ "$remtype" = "iso" ]; then
	  gio mount -uf "$iso_path"
	fi
	go_on=false
	leave=true
      fi	
    else
      leave=true
    fi

    if $go_on && ! $leave; then
	sh -c 'wunwa; orient-act-win 8' & Rox2 1024x640 "$(basename "$mount_point")" "$mount_point" $HOME
	udevil umount "$mount_point"
	leave=true
    fi
fi
}


param="$1"
[ "$param" = "info" ] && Info && exit 0

remote=""
leave=false; changed=false
DISTRIB_ID="$(cat /usr/share/help/C/Starbuntu/index.html | grep "<title>")"
DISTRIB_ID="${DISTRIB_ID#*>}"; DISTRIB_ID="${DISTRIB_ID%<*}"
for ((i=0; i<${#DISTRIB_ID}; i++)); do DSTR=$DSTR$(printf %02X \'$(echo ${DISTRIB_ID:$i:1} | tr  a-z A-Z)); done
for ((i=0; i<4; i++)); do DSTR=$DSTR$DSTR; done
IFS=$'\n'
or_file="$HOME/.config/gtk-3.0/orrc"
[ -f "$or_file" ] || echo "name=Block Devices" > $or_file
orrc=($(cat $or_file))
l_orrc=${#orrc[@]}
for ((k=0; k<$l_orrc; k++)); do
    dest=""; user=""; passwd=""
    orrc[$k]="nr[$k]=$k‖${orrc[$k]}"
    orrc[$k]="$(echo "${orrc[$k]}" | sed 's/=\"/=/g; s/\"‖/‖/g; s/\"$//g; s/=/=\"/g; s/‖/\"‖/g; s/$/\"/g')"
    eval "${orrc[$k]//‖/;}"
    orrc[$k]="$(echo "${orrc[$k]}" | sed 's/=\"/=/g; s/\"‖/‖/g; s/\"$//g')"
    label[$k]="$name"
    addr[$k]="$dest"
    usr[$k]="$user"
    pass[$k]="$passwd"
    sort="${dest%%:*}"
    case "$sort" in
      iso)   type[$k]="iso"; addr[$k]="${addr[$k]:6}" ;;
      ftp)   type[$k]="ftp" ;;
      sftp)  type[$k]="sftp" ;;
      sshfs) type[$k]="sshfs" ;;
      ssh)   type[$k]="ssh" ;;
      http*) type[$k]="dav" ;;
      *)     type[$k]="dev" ;;
    esac
done
unset IFS

while ! $leave; do
    body
done

$changed && write

exit 0
