# -*- mode: shell-script -*-

HUGO_CONFIG="/etc/hugo"
HUGO_BASE="/opt/apps/hugo"
HUGO_SOURCE="$HUGO_BASE/src"
HUGO_OUTPUT="$HUGO_BASE/output"
HUGO_THEME="$HUGO_BASE/theme"


HOST_HUGO_SOURCE="$SERVICE_DATASTORE$HUGO_BASE/src"
HOST_HUGO_OUTPUT="$SERVICE_DATASTORE$HUGO_BASE/output"
HOST_HUGO_THEME="$SERVICE_DATASTORE$HUGO_BASE/theme"
HOST_HUGO_CONFIG="$SERVICE_CONFIGSTORE$HUGO_CONFIG"

HUGO_BUILDER_DEFAULT_IMAGE="docker.0k.io/hugo:0.88.1"


hugo:init-dir() {
    mkdir -p "$HOST_HUGO_SOURCE" || return 1
    cd "$HOST_HUGO_SOURCE" &&
    git config --global user.email "compose@mail.com" &&
        git config --global user.name "compose"  &&
        docker run --rm -v "$HOST_HUGO_SOURCE":"$HUGO_SOURCE" \
               -w "$HUGO_SOURCE" "$HUGO_BUILDER_DEFAULT_IMAGE" \
               new site -f yaml . &&
        docker run --rm -v "$HOST_HUGO_SOURCE":"$HUGO_SOURCE" \
               -w "$HUGO_SOURCE" "$HUGO_BUILDER_DEFAULT_IMAGE" \
               new posts/my-first-post.md &&
        sed -ri '/^baseURL:/d' config.yaml &&
        git init &&
        git add -A . &&
        git commit -m "First import"
}


hugo:generate() {
    local src="$1" dst="$2" configs c

    theme_url=$(options-get theme-url 2>/dev/null) || true
    theme_url=${theme_url:-https://github.com/theNewDynamic/gohugo-theme-ananke.git}

    if ! [ -d "$HOST_HUGO_THEME/default" ]; then
        mkdir -p "$HOST_HUGO_THEME"
        git clone "${theme_url}" "$HOST_HUGO_THEME/default" || {
            err "Could not clone theme '$HOST_HUGO_THEME'."
            return 1
        }
    fi
    echo "theme: default" > "$HOST_HUGO_CONFIG/80-theme.yaml"
    config_files=("$HOST_HUGO_CONFIG/"*.yaml)
    configs=""
    for c in "${config_files[@]}"; do
        configs+="config${c#$SERVICE_CONFIGSTORE$HUGO_CONFIG},"
    done
    mkdir -p "$dst" || return 1
    docker run --rm -v "$src":"$HUGO_SOURCE" \
           -v "$dst":"$HUGO_OUTPUT" \
           -v "$HOST_HUGO_CONFIG":"$HUGO_CONFIG" \
           -v "$HOST_HUGO_THEME":"$HUGO_SOURCE/themes" \
           -v "$HOST_HUGO_CONFIG":"$HUGO_SOURCE/config" \
           -w "$HUGO_SOURCE" "$HUGO_BUILDER_DEFAULT_IMAGE" \
           -D --config "${configs}config.yaml" \
           -d "${dst#$SERVICE_DATASTORE}" &&
    find "$HOST_HUGO_SOURCE" -depth -type d -empty -delete
}