#!/bin/bash
set -euo pipefail
# Read all
# NC_SHARE_LINK_URL.*
# NC_SHARE_LINK_PASSWORD.*
# NC_SHARE_LINK_DESTINATION.*
# With .* equals

while IFS='=' read key value ; do
	# suffix of sharer link
	name="${key#NC_SHARE_LINK_URL}"
	echo "Rcloning $name..."

	password_varname="NC_SHARE_LINK_PASSWORD$name"
	destination_varname="NC_SHARE_LINK_DESTINATION$name"

	# Empty by default
	url="${!key}"
	password="${!password_varname:-}"
	destination="${!destination_varname:-}"

	# Ensure we have a link
	if [ -z "$url" ] ; then
		echo "env var NC_SHARE_LINK_URL$name is empty."
		exit 1
	fi

	# Ensure we have a destination
	if [ -z "$destination" ] ; then
		echo "env var NC_SHARE_LINK_DESTINATION$name is empty."
		exit 1
	elif [ ! -d "$destination" ] ; then
		mkdir "$destination"
	fi

	# Get content from nextcloud
	webdav_url="$(echo "$url" | sed 's#/s/.*#/public.php/webdav/#')"
	webdav_user="$(echo "$url"  |sed 's#.*/s/##')"
	webdav_pass="$(rclone obscure "$password")"
	
	rclone sync --config=/notfound --webdav-url="$webdav_url" --webdav-user="$webdav_user" --webdav-pass="$webdav_pass" --webdav-vendor=nextcloud :webdav: "$destination"
	
	# Go to website
	cd "$destination"
	
	# Rename .attachement dirs created by nextcloud
	while read filename ; do    
	    oldname="$(basename "$filename")"    
	    newname="${oldname:1}"    
	    path="$(dirname "$filename")"    
	    # And rename their references in md files  
	    find "$path" -type f -iname '*.md' -exec sed -i "s/$oldname/$newname/g" {} \;    
	    mv "$path/$oldname" "$path/$newname"    
	done < <(find -type d -name '.attachments.*')

	cd - &>/dev/null
	echo "Rcloning done!"
done < <(env | grep ^NC_SHARE_LINK_URL )