#!/bin/bash

# Title......: site
# Description: script to build and manage website from markdown files
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Thu 29 Aug 2024 06:18:48 AM CDT
#----------------------------------

: ' Changes
Mon May 06 2024 - Added markdown formatted help
Sat Feb 10 2024 - Removed file version control
Sat Feb 10 2024 - Added new version()
Sun Nov 19 2023 - Changed method for video of day selection
Thu Oct 19 2023 - Having an issue still, but back to vim. Seems to be a bug with pandoc syntax plugin.
Wed 18 Oct 2023 - Switched to Midnight Commander editor, having an issue with Vim and large MarkDown files.
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
PS4='$SECONDS $LINENO: '                   # debug prompt
INCLUDE=/var/www/include                   # location of header and footer files       
CURRENT=$PWD
TITLE="$(echo $DIR|cut -d'.' -f1|tr '-' ' '|sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g')"
NAME=${0##*/}                              # name of the script
PDOCOPT="--from=markdown+emoji+lists_without_preceding_blankline+autolink_bare_uris"
VIDS=/var/www/include/vids                 # location of videos
CSS=/var/www/crn.css                       # site css file
export FZF_DEFAULT_OPTS="--ansi --prompt='▶' --pointer='→' --marker='♡' --preview-window 'right:60%' --preview 'bat --color=always --style=header,grid --line-range :300 {} 2>/dev/null'"

# functions
#----------------------------------

html(){ ## mark up code
    vim -f +"syn on" +"colorscheme termschool" +"set nonu" +"set foldenable!" +"set nospell" +"run! syntax/2html.vim" +"wq" +"q" $1
}

bl(){ ## make blank line
    echo ""
}

compile(){ ## create html from markdown, $1 is name of markdown file
	[ "$DEBUG" == "1" ] && set -x
	PAGE="${1%.md}"    # Get the first name, remove .md if it was added
	[ $(egrep -c '^Updated:' $PAGE.md) -eq 1 ] && sed -i -e "s/^Updated:.*/Updated: $(date)/" $PAGE.md
	pandoc "$PDOCOPT" "${PAGE}.md" -o $$.html             # convert markdown to html
    cp $$.html include.html
	if [ -f "$INCLUDE/${PAGE}_header.html" ]
	then
		cat "$INCLUDE/${PAGE}_header.html" >"${PAGE}.html"  # create new html file with header
	else
        if [ "$PWD" =  "/var/www/unix" ]
        then
            cat "$INCLUDE/unix_header.html" >"${PAGE}.html"  # create new html file with header
        else
            cd $INCLUDE
            CHOICE=$(ls *header* |fzf --ansi --prompt='▶' --pointer='→' --marker='♡' --reverse --color fg:-1,bg:-1,hl:46,fg+:40,bg+:233,hl+:46 --color prompt:166,border:46 --height 70%  --border=sharp --prompt="Header ➤  " --pointer="➤ " --marker="➤ ")
            cd -
            [ ! -f "${INCLUDE}/${CHOICE}" ] && exit 2
            cat "$INCLUDE/$CHOICE" >"${PAGE}.html"  # create new html file with header
        fi
	fi
	cat $$.html >>"${PAGE}.html"                     # add new content
	cat "$INCLUDE/footer.html" >>"${PAGE}.html"         # add footer
	[ -d "$PAGE" ] && cp ${PAGE}.html ${PAGE}/index.html
	rm $$.html                                    # remove tmp file
}

pause(){ ## simple pause routine
	# Use: pause  {optional number of seconds} or "-nt" for no time out 
	[ "$DEBUG" == "1" ] && set -x
	[ "$1" == "-nt" ] && TMOUT="" && shift
    echo "$BY";
    if [ $# -gt 0 ]
	then
		read -t $1 -r -p "${C}Hit any key (${BY}$1${C} second timeout)${N}" -n 1 FOO;
    else
		read -r -p "${C}Hit any key${N}" -n 1 FOO;
    fi;
    bl
}

xtitle(){ ## set window title
	# Use: xtitle "Text to display"
    printf "\033]0;%s\007" "$*"
}

log(){ ## creates a basic log entry $LOG must be defined
	# Use: log {entry}  
	[ "$DEBUG" == "1" ] && set -x
	logger -i -t "$NAME" "$*"
}

version(){ ## display version and change history
    grep -E '^# Updated' $0
    bl
    sed -n "/' Changes/,/^ *$/p" <$0 |grep  -E -v 'sed -n|exit 0|}'
    exit 0
}

# setup
#----------------------------------

# this provides a quick way to edit all my scripts on the fly
if [ "$1" == "-E" ]
then
	vim $0
	sed -i -e "7s/.*/# Updated....: $(date)/" $0
	log "updated $0"
    html $0
    cp $0 /var/www/unix
    mv $0.html /var/www/unix
    cp $0 /var/gopher/scripts
	exit
fi

# display help if needed
if [ "$1" == "-h" ] || [ "$1" == "--help" ]
then
glow <<END
# $NAME

_Part of a framework to mange a markdown based website in Linux_

|Option|Description|
|------|-----------|
|-a|Remake entire site|
|-c|{file} # compile with no user input |
|-C|Edit site css file: $CSS|
|-d|{optional mp4} Daily update quotes, video of the day, random video if not passed one|
|-l|List markdown files|
|-m|{file} # edit, make file; if no input gives selection menu|
|-v|Display version|

END
exit
fi

# display version and change history
if [ "$1" == "-v" ] || [ "$1" == "--version" ]
then
    version
fi

# listing of required apps
command -v pandoc >/dev/null || sudo apt install pandoc -yyq # https://pandoc.org/installing.html 
command -v fzf >/dev/null || sudo apt install fzf -yyq       # https://github.com/junegunn/fzf
command -v glow >/dev/null || sudo apt install glow -yyq     # https://github.com/charmbracelet/glow



# main
#--------------------------- 
[ "$DEBUG" == "1" ] && set -x

case $1 in
	-a) # remake entire site
		# main pages
		cd /var/www || exit 1
		for MD in $(ls *md)
		do
			compile "$MD"
			log "compiled: $MD"
		done
		;;
	-c) # compile no user input
		shift
		for FILE in "$*"
		do
			compile $FILE 
			log "compiled: $FILE"
		done
		;;
    -C) # edit css file
        vi $CSS
        ;;
	-d) # daily update
        #[ "$(date +%H)" != "00" ] && echo "Time error $(date)" && exit 1
		cd /var/www || exit 1  # I can run this from anyplace, and it works.
		sed -i -e "3s#.*#:scroll: $(quote -w)#" links.md # update quote on # line
		sed -i -e "7s#.*#:scroll: $(quote -w)#" index.md # update quote on # line
		sed -i -e "13s#.*#:black_nib: $(bd)#" books.md # update word of day on # line 
		VOD=$(grep  -m 1 -n vids index.md|cut -d':' -f1) # get the line no for 1st video on page
		if [ "$#" -eq 2 ] # if passed a video, use it, else random
		then
			sed -i -e "${VOD}s#.*#$(pi $2)#" index.md # update 1st video
			log "VOD: $2"
		else
			sed -i -e "${VOD}s@.*@$(rvid)@" index.md # update 1st video
			log "VOD: Random"
		fi	
		compile index                # compile them
		compile links
		compile books
        # update proverbs link
        sed "s/prv-$(date -d "1 day ago" +%e)/prv-$(date +%-e)/" /var/www/proverbs/index.html >/var/www/proverbs/index.new && mv /var/www/proverbs/index.new /var/www/proverbs/index.html
		# update news link
        \rm news
		ln -s include/vids/clips/$(date +%a|tr [A-Z] [a-z])  news
		cd /var/www/include/vids/clips && mkindex
		cd .. && mkindex
        # Change tank
        /var/www/clock5/switch
        # gopher
		cd /var/gopher    
		gmap
		log "Daily update"
		;;
    -l) # list markdown files
        cd /var/www && grep --color 'Updated:' *.md
        cd -
        ;;
	-m) # compile with manual update
		cd /var/www || exit 1  # I can run this from anyplace, and it works.
		if [ "$#" -eq 2 ]
		then
			FILE="${2%.md}" 
			[ ! -f $FILE.md ] && exec $0 -m # if the file does not exist, restart w/o it
			vim $FILE.md
			compile $FILE
			log "Updated $FILE"
		else
			clear
			CHOICE=$(ls *md|fzf -m --prompt='▶' --pointer='→' --marker='♡' --ansi --color fg:-1,bg:-1,hl:46,fg+:40,bg+:233,hl+:46 --color prompt:166,border:46 --height 70%  --border=sharp --prompt="➤  " --pointer="➤ " --marker="➤ " --preview '(highlight -O ansi {} || bat {}) 2> /dev/null | head -500')

			echo "$CHOICE"|tr '\n' ' ' >/tmp/$$ 
			for FILE in $(cat /tmp/$$)
			do
				vim $FILE
				compile $FILE
				log "Updated $FILE"
			done
		fi
		;;
	*) # display help
		$NAME -h
		;;
esac

exit