#!/bin/bash

. driglibash-base

set -euo pipefail

[ "$#" -ne 1 ] && die "Usage: $0 <hugo_directory>"
dest_dir="$1"
[ -z "$dest_dir" ] && die "Arg 'hugo_directory' should not be empty."


# Get content from nextcloud
if [ -v NC_SHARE_LINK ] ; then
	webdav_url="$(echo "$NC_SHARE_LINK" | sed 's#/s/.*#/public.php/webdav/#')"
	webdav_user="$(echo "$NC_SHARE_LINK"  |sed 's#.*/s/##')"
	webdav_pass="$(rclone obscure "$NC_SHARE_PASSWORD")"

	rclone sync --config=/notfound --webdav-url="$webdav_url" --webdav-user="$webdav_user" --webdav-pass="$webdav_pass" --webdav-vendor=nextcloud :webdav: "$dest_dir/$CLOUD_LOCAL_PATH"
fi

# Go to website
cd "$dest_dir"

# 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 -type f -iname '*.md' -exec sed -i "s/$oldname/$newname/g" {} \;    
    mv "$path/$oldname" "$path/$newname"    
done < <(find -type d -name '.attachments.*')

# Build the website
hugo --ignoreCache
