#!/bin/sh

create_ls_entry () {
    echo "creating entry $(pwd)$1"
    echo "#+title: =~/$1=" > index.org
    echo "* Directories" >> index.org
    if [ "$1" != "" ]; then
        echo "- [[../][=../=]]" >> index.org
    fi
    find -L -- . -maxdepth 1 -type d | sed '/^\.$/d' | sed 's/^\.\///' | sort | while read -r dir; do
        if [ "$dir" != "*" ] && [ "$dir" != ".git" ]; then
            echo "- [[./$dir][=$dir/=]]" >> index.org
        fi
    done
    files=$(find -L -- . -maxdepth 1 -type f | sed 's/^\.\///')
    if [ "$files" != '' ]; then
        echo '* Files' >> index.org
        echo "$files" | sort | while read -r file; do
            if echo "$file" | grep -q '^\.'; then
                tmp=$(echo "$file" | sed 's/^\.//' | sed 's/.org$/.hidden.org/')
                mv "$file" "$tmp"
            fi
            if [ "$file" = ".wallpaper" ]; then
                echo "- [[https://wallhaven.cc/w/n66pex][=.wallpaper=]]" >> index.org
            elif echo "$file" | grep -q "\.org$" && [ "$file" != "index.org" ]; then
                new_file=$(echo "$file" | sed 's/\.org$//')
                html=$(echo "$file" | sed 's/\.org$/\.html/')
                echo "- [[./$html][=$new_file=]]" >> index.org
            fi
        done
    fi
}

create_dir_tree () {
    ROOT="$HOME/dotfiles/$1"
    create_ls_entry ""

    # iterate over all directories
    find -L -- . -type d | sed '/^\.$/d' | while read -r dir; do
        cd "$dir" || continue

        dir=$(echo "$dir" | sed 's/^\.\///')

        create_ls_entry "$dir/"

        cd "$ROOT" || exit
    done
}

cd ~/dotfiles || exit
git checkout main
echo '#+title: Dotfiles' > index.org
echo 'This is my system configuration. These pages are automatically generated from the sources hosted [[https://git.sr.ht/~jjanzen/dotfiles][here]]. Choose which system to browse: ' >> index.org
find -- . -maxdepth 1 -type d | sed '/\(^\.$\|^\.\/\.git$\|\.\/common\)/d' | while read -r root; do
    echo creating root "$root"
    root=$(echo "$root" | sed 's/\(\.\/\|\/$\)//')
    echo root after cleanup: "$root"
    echo "- [[./${root}][${root}]]" >> index.org
    cd "$root" || exit
    create_dir_tree "$root"
    cd ~/dotfiles || exit
done

cd || exit
