#!/bin/bash
#
###########################################################################
# Description: SUSE branded pandoc build script
# Version: 2024-08-27.1
# Author: Raine Curtis <raine.curtis@suse.com>
###########################################################################
#
# Output formats:
# usage: supan [pdf|docx|odt|html]
###########################################################################
# Global variables
DEFAULTS=".supan"
MODE=""
PRJLOC="" 
PRJDIR=""
PRJTITLE="" 
PRJSUBTITLE="" 
PRJFILE=""
DOC=""
OUTDOC=""
AUTHOR=""
AUTHORTITLE=""
SUPAN_SHARE="/usr/share/supan"
SUPAN_RESOURCES=""
#BTIME=$(date +"%Y-%m-%d_%H-%M")
BTIME=$(date +"%Y-%m-%d")
# Formatting:
NC="\033[0m"
BOLD="\033[1m"
BLACK='\E[30'
RED='\E[31m'
GREEN='\E[32m'
YELLOW='\E[33'
BLUE='\E[34m'
MAGENTA='\E[35m'
CYAN='\E[36m'
WHITE='\[37;47m'
PURPLE='\033[0;35m'
ORANGE='\033[0;33m'
###########################################################################
echo -e "${GREEN}${BOLD}### SUSE pandoc document utility ###${NC}"

function show_debug () {
    msg=$1
    ### Uncomment the following line for debugging ###
    #echo -e "#${PURPLE} - $(date)${BLACK} # ${BLUE} ${msg}${NC}"
}

function cleanup () {
    echo -e "${BLUE}Cleaning up output documents${NC}"
    set_md_file
    show_debug "DOC->$DOC"
    if [[ -f $DOC ]]; then
        OUTDOC="${DOC%.*}"
        rm -f ${OUTDOC}*.pdf ${OUTDOC}*.docx ${OUTDOC}*.odt ${OUTDOC}*.html 
    fi
}

function build_pdf () {
    echo -e "${BLUE}Building pdf document${NC}"
    set_md_file
    set_output_doc pdf
    set_run_env
    pandoc --include-in-header=${SUPAN_SHARE}/resources/header.tex --highlight-style=${SUPAN_SHARE}/resources/suse.theme --metadata date="$(date "+%B %d, %Y")"   --table-of-contents   --number-sections -V mainfont="Poppins" -V monofont="DejaVu Sans Mono" -V colorlinks -V linkcolor="RedOrange"  -V urlcolor="NavyBlue" -V toccolor="PineGreen" -V geometry:"top=1in, bottom=1in, left=1in, right=1in"  ${DOC} -o ${OUTDOC} 
    if (( $? == 0 )); then
        echo -e "${GREEN}SUCCESS: ${NC}Created ${BLUE}$OUTDOC${NC}"
    else
        echo -e "${RED}FAILED: ${NC}in creating ${ORANGE}$OUTDOC${NC}"
    fi
}

function build_odt () {
    echo -e "${BLUE}Building odt document${NC}"
    set_md_file
    set_output_doc odt
    set_run_env
    pandoc --include-in-header=${SUPAN_SHARE}/resources/header.tex --reference-doc=${SUPAN_SHARE}/resources/suse-white-paper-template.odt  --highlight-style=${SUPAN_SHARE}/resources/suse.theme --metadata date="$(date "+%B %d, %Y")" --table-of-contents --number-sections -V toc-title:"Table of Contents" -V mainfont="Poppins" -V monofont="DejaVu Sans Mono" -V colorlinks -V linkcolor="RedOrange"  -V urlcolor="NavyBlue" -V toccolor="PineGreen" -V geometry:"top=1in, bottom=1in, left=1in, right=1in" ${DOC} -o ${OUTDOC} 
    if (( $? == 0 )); then
        echo -e "${GREEN}SUCCESS: ${NC}Created ${BLUE}$OUTDOC${NC}"
        echo -e "${ORANGE}After opening the document right-click on the 'Table of Contents' and select 'Update Index'.${NC}"
    else
        echo -e "${RED}FAILED: ${NC}in creating ${ORANGE}$OUTDOC${NC}"
    fi
}
function build_docx () {
    echo -e "${BLUE}Building pdf document${NC}"
    set_md_file
    set_output_doc docx
    set_run_env
    pandoc --include-in-header=${SUPAN_SHARE}/resources/header.tex --reference-doc=${SUPAN_SHARE}/resources/suse-white-paper-template.docx  --highlight-style=${SUPAN_SHARE}/resources/suse.theme --metadata date="$(date "+%B %d, %Y")" --table-of-contents --number-sections -V mainfont="Poppins" -V monofont="DejaVu Sans Mono" -V colorlinks -V linkcolor="RedOrange"  -V urlcolor="NavyBlue" -V toccolor="PineGreen" -V geometry:"top=1in, bottom=1in, left=1in, right=1in" ${DOC} -o ${OUTDOC} 
    if (( $? == 0 )); then
        echo -e "${GREEN}SUCCESS: ${NC}Created ${BLUE}$OUTDOC${NC}"
        echo -e "${ORANGE}After opening the document right-click on the 'Table of Contents' and select 'Update Index'.${NC}"
    else
        echo -e "${RED}FAILED: ${NC}in creating ${ORANGE}$OUTDOC${NC}"
    fi
}

function build_html () {
    echo -e "${BLUE}Building html document${NC}"
    set_md_file
    set_output_doc html
    set_run_env
    pandoc --standalone  --highlight-style=${SUPAN_SHARE}/resources/suse.theme --css=${SUPAN_SHARE}/resources/suse.css --metadata date="$(date "+%B %d, %Y")"   --table-of-contents   --number-sections -V toc-title:"Contents" -V mainfont="Poppins" -V monofont="DejaVu Sans Mono" -V colorlinks -V linkcolor="RedOrange"  -V urlcolor="NavyBlue" -V toccolor="PineGreen" -V geometry:"top=1in, bottom=1in, left=1in, right=1in"  ${DOC} -o ${OUTDOC} 

    if (( $? == 0 )); then
        echo -e "${GREEN}SUCCESS: ${NC}Created ${BLUE}$OUTDOC${NC}"
    else
        echo -e "${RED}FAILED: ${NC}in creating ${ORANGE}$OUTDOC${NC}"
    fi
}

function set_md_file () {
    MDFILES=($(ls $PWD/*.md 2>/dev/null))
    for md in "${MDFILES[@]}" 
    do
        show_debug "FOUND: -> $md"
    done
    show_debug "MDFILES size: ${#MDFILES[@]}"
    if (( ${#MDFILES[@]} ==  0 )); then
        echo -e "${RED}No source markdown file found. Change to the directory of the markdown file and run again${NC}."
        exit 1
    elif (( ${#MDFILES[@]} ==  1 )); then
        DOC=${MDFILES[0]}
        show_debug "MD DOC set to: $DOC"
    else
        echo -e  "${ORANGE}Multiple source files found${NC}"
        SF=""
        while [[ -z ${SF} ]]
        do
            for ((i=0; i<${#MDFILES[@]}; i++)); do
                echo "${i} ) ${MDFILES[$i]}"
            done
            read -p "Enter the number for the file you want to use: " SF
            show_debug "$SF"
            if (( $SF < ${#MDFILES[@]} )) &&  (( $SF >= 0 )); then
                DOC=${MDFILES[$SF]}
                show_debug "DOC: $DOC"
            else
                SF=""
            fi
        done
    fi
}

function set_output_doc () {
    EXT="$1"
    show_debug "Setting output document"
    OUTDOC="${DOC%.*}-${BTIME}.${EXT}"
    show_debug "OUTDOC: $OUTDOC"
}

function set_run_env () {
    if [[ -d ${PWD}/resources ]]; then
        SUPAN_RESOURCES="${PWD}/resources"
    else
        SUPAN_RESOURCES="${SUPAN_SHARE}/resources"
    fi
}

function create_new_project () {
    PRJLOC=$PWD
    PRJTITLE_DEFAULT="SUSE Document Title"
    PRJSUBTITLE_DEFAULT="SUSE SubTitle"
    show_debug "Creating new project"
    while true
    do
        echo -e "${BOLD}${GREEN}############# New Project Settings ################${NC}"
        # Get project location
        printf "${BOLD}${ORANGE}Project location ${NC}[${PURPLE}${PRJLOC}${NC}]: "
        read -p "$pmsg " PRJLOC
        PRJLOC=${PRJLOC:-$PWD}
        # Get project name (title)
        printf "${BOLD}${ORANGE}Document Title ${NC}[${PURPLE}${PRJTITLE_DEFAULT}${NC}]: "
        read -p "$pmsg " PRJTITLE
        PRJTITLE=${PRJTITLE:-$PRJTITLE_DEFAULT}
        PRJTITLE_DEFAULT=$PRJTITLE
        # Get project (subtitle)
        printf "${BOLD}${ORANGE}Document SubTitle ${NC}[${PURPLE}${PRJSUBTITLE_DEFAULT}${NC}]: "
        read -p "$pmsg " PRJSUBTITLE
        PRJSUBTITLE=${PRJSUBTITLE:-$PRJSUBTITLE_DEFAULT}
        PRJSUBTITLE_DEFAULT=$PRJSUBTITLE
        # Set project file name
        # Convert to lower
        PRJFILE="$(echo $PRJTITLE | tr '[:upper:]' '[:lower:]')"
        # Replace spaces with _
        PRJFILE="$(echo $PRJFILE | tr ' ' '_').md"
        # Ask if correct
        echo -e "${BOLD}${GREEN}--------------------------------------------${NC}"
        echo -e "${GREEN}Project Location: $BLUE $PRJLOC $NC"
        echo -e "${GREEN}Project Title: $BLUE $PRJTITLE $NC"
        echo -e "${GREEN}Project SubTitle: $BLUE $PRJSUBTITLE $NC"
        echo -e "${GREEN}Project File: $BLUE $PRJFILE $NC"
        echo -e "$BOLD ${BLUE}"
        read -p "Are these values correct? (Y/n): " yn 
        echo -e "$NC"
        case $yn in 
            [yY] ) 
                build_project 
                exit;;
            [nN] ) 
                continue;;
            * ) 
                build_project 
                exit;;
        esac
    done
}

function build_project () {
    show_debug "Building Project"
    PRJDIRNAME=${PRJFILE%.*}
    PRJDIR=${PRJLOC}/${PRJDIRNAME}
    show_debug "Project Directory: $PRJDIR"
    if [[ -d $PRJDIR ]]; then
        echo "Directory already exists"
        read -p "Overwrite? (y/N): " yn
        while true
        do
            case $yn in 
                [yY] ) 
                    break;;
                [nN] ) 
                    echo -e "${RED}Aborting operation${NC}"
                    exit;;
                * ) 
                    echo -e "${RED}Aborting operation${NC}"
                    exit;;
            esac
        done
    fi
    show_debug "Creating directory: $PRJDIR"
    mkdir -p $PRJDIR
    create_supan_doc
    copy_template
}

function copy_template () {
    show_debug "Copying supan template"
    if [[ -d /usr/share/supan ]]; then
        show_debug "cp -af ${SUPAN_SHARE}/images/ $PRJDIR/"
        cp -af ${SUPAN_SHARE}/images/ $PRJDIR/
        if [[ "$MODE" == "new-standalone" ]]; then
            cp -af /usr/share/supan/resources/ $PRJDIR/
            echo
        fi
    fi
}

function create_supan_doc () {
   show_debug "Creating document: $PRJDIR/$PRJFILE "
   cat > $PRJDIR/$PRJFILE <<- _EOF_
---
##################################################################
# YAML Header for document metadata
##################################################################
# Document class can be [article | report]
documentclass: article
title:  |
        $PRJTITLE \\
        \\
        ![](images/suse-logo.png){width="100px" margin-right="auto"  margin-left="auto"} \\
author: ${AUTHOR}, ${AUTHORTITLE}
subtitle: "$PRJSUBTITLE"
abstract: ADD A DOCUMENT ABSTRACT HERE.
classoption:
- landscape
# - twocolumn
description: Generated by supan


##################################################################
# Document in markdown starts below  (dots) ...
##################################################################
...

# Level 1 Header

*Sample content.*

The **summary** of the *document*.



## Level 2 Header Showing Example Console

Here is a ``sample console`` output:

\`\`\`sh {.numberLines}
#!/bin/bash
echo "Running Script"
\`\`\`

### Level 3 Header Showing a Table

Here is a table.

| **Time** | **Description**                                                   |
| -------- | ----------------------------------------------------------------- |
| 17:21    | Failure...                                                        |
| 17:21    | SAPHana: HANA_CALL of \`\`systemReplicationStatus.py\`\` times out    |

#### Level 4 Header Showing References

Here is one for Figure \\ref{suse-logo} SUSE Logo.

![SUSE Logo \\label{suse-logo}](./images/suse-logo.png){width=2in}


\newpage 

# Referencing Sections

Here is a reference to [First Header](#level-1-header) at the top.

Here is a link to an external site of [SUSE](https://www.suse.com)

Here is a footnote to a Markdown Guide.[^1] 

[^1]: SUSE Support is found at [https://www.suse.com/support/handbook/](https://www.suse.com/support/handbook/)

_EOF_

}

function chk_defaults () {
    show_debug "Checking defaults"
    if [[ ! -f ${HOME}/${DEFAULTS} ]]; then
        set_defaults
    else
        get_defaults
    fi
}

function get_defaults () {
    show_debug "Getting supan defaults"
    AUTHOR=$(grep 'AUTHOR=' ~/.supan  |awk -F= '{print $2}')
    AUTHORTITLE=$(grep 'AUTHORTITLE=' ~/.supan  |awk -F= '{print $2}')
    echo "AUTHOR: $AUTHOR"
    echo "AUTHORTITLE: $AUTHORTITLE"
}

function set_defaults () {
    show_debug "Set defaults for supan"
    # Author name
    while [[ -z $AUTHOR ]]
    do
        printf "${BOLD}${ORANGE}Enter author full name: ${NC}"
        read -p "$pmsg " AUTHOR
    done
    # Author title
    while [[ -z $AUTHORTITLE ]]
    do
        printf "${BOLD}${ORANGE}Enter author title: ${NC}"
        read -p "$pmsg " AUTHORTITLE
    done
    cat > ${HOME}/${DEFAULTS} <<- _EOF_
AUTHOR=${AUTHOR}
AUTHORTITLE=${AUTHORTITLE}
_EOF_
}

function usage () {
    cat <<- _EOF_
# Overview
Document build system based on pandoc that creates a SUSE 
branded markdown document.

## Defaults
The first run asks for document defaults for:
AUTHOR
AUTHOR TITLE that will be used in all documents.

These values can be viewed by running:
> supan get-defaults

These values can be set/changed by running:
> supan set-defaults

# New Source Markdown Document
Create an new supan document:
> supan new

Create a new stand-alone document:
> supan new-stand-alone

# Generating Output Documents
All output documents are named by the date.
An output pdf file can be generat4ed by running:
> supan pdf

An output html file can be generat4ed by running:
> supan html

An output docx file can be generat4ed by running:
> supan docx

An output odt file can be generat4ed by running:
> supan odt

All output formats can be generated by running:
> supan build-all

All output documents can be cleaned up by running:
> supan clean

_EOF_
}

### Main ###
show_debug "$PWD"
# Get command-line arguments
show_debug "$#"
if (( $# >= 2 )); then
    show_debug "MODE: $1"
fi
i=1
for arg in "$@"
do
    show_debug "$i: $arg"
    i=$((i+1))
    case "${arg}" in
        "new")
            MODE="new"
            chk_defaults
            create_new_project
            ;;
        "new-standalone")
            MODE="new-standalone"
            chk_defaults
            create_new_project
            ;;
        "set-defaults")
            set_defaults
            ;;
        "get-defaults")
            get_defaults
            ;;
        "clean")
            cleanup
            ;;
        "pdf")
            MODE="pdf"
            build_pdf
            ;;
        "html")
            MODE="html"
            build_html
            ;;
        "docx")
            MODE="docx"
            build_docx
            ;;
        "odt")
            MODE="odt"
            build_odt
            ;;
        "build-all")
            MODE="pdf"
            build_pdf
            MODE="html"
            build_html
            MODE="docx"
            build_docx
            MODE="odt"
            build_odt
            ;;
        "help")
            usage
            ;;
    esac
done

