#!/bin/bash

tmpfile=/tmp/tmp_myfile_$USER__$$

cd "$( dirname "$0" )"

for f in *.md; do
    if head "$f" | grep -q "^# "; then
        echo
        echo ">>>>> FIX $f"
        echo
        cp -p "$f" "$tmpfile"

        if grep -q "^## Introduction" "$f"; then
            echo "Replace '## Introduction'"
            sed -i -e "s/^## Introduction.*//" "$tmpfile"
            head -1 "$f" | tail -1 | grep  "." &&  sed -i -e '2,3d' "$tmpfile"

            # make 1st h1 smaller
            sed -i -e "0,/^# /{s/^# /## /}" "$tmpfile"

        else
            echo "Move Headers"
            if grep "^###### " "$f"; then
                echo "ABORT: H6 was found that cannot moved to smaller level."
                exit 1
            fi
            for header in "#####" "####" "###" "##" "#"
            do
                sed -i -e "s/^$header /#$header /g" "$tmpfile"
            done
        fi
        diff -u --color "$f" "$tmpfile"
        echo
        read -p "Apply changes on '$f' [Y/n]? > " apply
        if [ "$apply" = "" ] || [ "$apply" = "y" ]|| [ "$apply" = "Y" ]; then
            echo "Applying ..."
            mv "$tmpfile" "$f"
        else
            echo "Keeping current version."
            rm "$tmpfile"
        fi
        sleep 1
        echo
        echo
        echo
        echo
        echo
        echo
        echo ----------------------------------------------------------------------
    else
        echo "OK $f"
    fi
done