#!/bin/bash
#-----------------------------------------------------------------------------------------------------------------------------------
#
# ISL: Image Stack Log
# 
# Copyright (C) 2026 Arnaud G. GIBERT
# mailto:arnaud@rx3.net
# 
# This is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; If not, see
# <https://www.gnu.org/licenses/>.
# 
#-----------------------------------------------------------------------------------------------------------------------------------



#-----------------------------------------------------------------------------------------------------------------------------------
# Includes
#-----------------------------------------------------------------------------------------------------------------------------------

: "${RX3_LIB_DIR:=/usr/lib/rx3}"
. "${RX3_LIB_DIR}/base.bash"





#-----------------------------------------------------------------------------------------------------------------------------------
# Global Variables
#-----------------------------------------------------------------------------------------------------------------------------------

declare -g   VERSION="1.1.1"
declare -g      NAME="ISL"
declare -g      HELP="usage: isl [-a | --add <URL>] | [-c | --cat [-r | --reverse]] | [-H | --html_dump [-i | --inline] [-r | --reverse]] | [-t | --top [-m | --image]] | [[-h | --help] | [-V | --version] [-T | --test] [-v | --verbose]"

declare -g  ISL_FILE="/etc/img_stack_log"
declare -g EXIT_CODE=0
declare -g      MODE="DEFAULT"
declare -g     IMAGE="FALSE"
declare -g    INLINE="FALSE"
declare -g   REVERSE="FALSE"
declare -g   URL=""





#-----------------------------------------------------------------------------------------------------------------------------------
# ISL Arg Parse
#-----------------------------------------------------------------------------------------------------------------------------------

function isl_args_parse()
{    
    tmp_args=$(getopt -o a:chHtVimrTv --long add:,cat,help,html-dump,top,version,image,inline,reverse,test,verbose -- "$@")

    if [ $? != 0 ] ; then echo_error "Terminating..."; exit 1 ; fi

    # Note the quotes around `$tmp_args': they are essential!
    eval set -- "${tmp_args}"

    while true ; do
	case "$1" in
            
	    # Options
            -i|--inline)                                     INLINE="TRUE";                       shift;;
            -m|--image)                                       IMAGE="TRUE";                       shift;;
            -r|--reverse)                                   REVERSE="TRUE";                       shift;;

	    # Mode switches
            -a|--add)                                          MODE="ADD";                        shift;  URL="$1"; shift;;
            -c|--cat)                                          MODE="CAT";                        shift;;
            -H|--html-dump)                                    MODE="HTML-DUMP";                  shift;;
	    -h|--help)                                         MODE="HELP";                       shift;;
            -t|--top)                                          MODE="TOP";                        shift;;
	    -V|--version)                                      MODE="VERSION";                    shift;;

	    # Global options
            -T|--test)                                      DRY_RUN="TRUE";                       shift;;
            -v|--verbose)                                   VERBOSE="TRUE";                       shift;;

	    #   
	    --)                                                                                   shift;  break;;
	    *) echo_error "args_parse internal error [$1] !"; exit 1;;
	esac
    done

    if [[ "${MODE}" == "DEFAULT" ]]
    then
        echo_error "A mode should be selected!"
        MODE="HELP"
        EXIT_CODE=1
    else
        if [[ "${REVERSE}" == "TRUE" ]]
        then
            if [[ ( "${MODE}" != "CAT") && ( "${MODE}" != "HTML-DUMP") ]]
            then
                echo_error "Reverse option only valid in Cat or HTML-Dump mode!"
                MODE="HELP"
                EXIT_CODE=1
            fi
        fi
        
        if [[ ( "${INLINE}" == "TRUE") && ( "${MODE}" != "HTML-DUMP") ]]
        then
            echo_error "Inline option only valid in HTML-Dump mode!"
            MODE="HELP"
            EXIT_CODE=1
        else
            if [[ ( "${IMAGE}" == "TRUE") && ( "${MODE}" != "TOP") ]]
            then
                echo_error "Image option only valid in Top mode!"
                MODE="HELP"
                EXIT_CODE=1
            fi
        fi
    fi
}





#-----------------------------------------------------------------------------------------------------------------------------------
# ISL Version Print
#-----------------------------------------------------------------------------------------------------------------------------------

isl_version_print()
{
    version_print
}





#-----------------------------------------------------------------------------------------------------------------------------------
# ISL Help Print
#-----------------------------------------------------------------------------------------------------------------------------------

isl_help_print()
{
    version_print
    help_print
}





#-----------------------------------------------------------------------------------------------------------------------------------
# ISL Print
#-----------------------------------------------------------------------------------------------------------------------------------

isl_print()
{
    local inline="$1"
    shift    
    
    
    if [[ "${inline}" == "TRUE" ]]
    then
        str="%s"'\\n'
    else
        str="%s"'\n'
    fi

    cmd_exec printf "${str}" "$*"
}





#-----------------------------------------------------------------------------------------------------------------------------------
# ISL Add
#-----------------------------------------------------------------------------------------------------------------------------------

isl_add()
{
    local url="$1"


    reg=${url%%/*}

    if [[ "${reg}" == *.* ]]
    then
        url=${url#*/}
    else
        reg="-"
    fi

     tag=${url/*:}
    name=${url%:*}

    if [[ "${tag}" == "${name}" ]]
    then
        echo_error "Bad tag format in URL!"
        return 1
    fi

    ts=$(date -u +"%Y/%m/%d %H:%M:%S")

    if [[ ! -e "${ISL_FILE}" ]]
    then
        id=1
    else
        id=$(( $(wc -l <"${ISL_FILE}") + 1))
    fi

    str="${id} ${ts} ${reg} ${name} ${tag}"

    if [[ $id == "1" ]]
    then
        sh_exec "echo \"${str}\" > \"${ISL_FILE}\""
    else
        cmd_exec sed -i '1i\'"${str}" "${ISL_FILE}"
    fi
}





#-----------------------------------------------------------------------------------------------------------------------------------
#  ISL Cat
#-----------------------------------------------------------------------------------------------------------------------------------

isl_cat()
{
    local reverse="$1"

    
    if [[ "${reverse}" == "TRUE" ]]
    then
        cmd_exec tac "${ISL_FILE}"
    else
        cmd_exec cat "${ISL_FILE}"
    fi
}





#-----------------------------------------------------------------------------------------------------------------------------------
# ISL HTML Dump
#-----------------------------------------------------------------------------------------------------------------------------------

isl_html_dump()
{
    local reverse="$1"
    local  inline="$2"

    local       i=1
    local       j=1

    
    i=1

    isl_cat "${reverse}" | while read line
    do
        set $line

        if [[ $(( $i % 2)) -eq 0 ]]
        then
            isl_print "${inline}" '            <tr class="shade">'
        else
            isl_print "${inline}" "            <tr>"
        fi

        j=1
        while [[ $j -lt 7 ]]
        do
            if [[ "$j" == "1" ]]
            then
                isl_print "${inline}" "              <th>${!j}</th>"
            else
                isl_print "${inline}" "              <td>${!j}</td>"
            fi

            j=$(( $j + 1))
        done

        isl_print "${inline}" "            </tr>"
        i=$(( $i + 1))
    done
}





#-----------------------------------------------------------------------------------------------------------------------------------
#  ISL Top
#-----------------------------------------------------------------------------------------------------------------------------------

isl_top()
{
    local image="$1"
    local  line=""

    
    line=$( head -1 "${ISL_FILE}")

    if [[ "$?" != "0" ]]
    then
        return 1
    else
        if [[ "${image}" == "TRUE" ]]
        then
            set ${line}
            
            sh_exec "echo \"$5:$6\""
        else
            sh_exec "echo \"${line}\""
        fi
    fi
}





#-----------------------------------------------------------------------------------------------------------------------------------
# Main
#-----------------------------------------------------------------------------------------------------------------------------------

orig_args=("$@")

isl_args_parse "$@"


case "${MODE}" in
            
    "EXIT")
        exit ${EXIT_CODE}
    ;;
    
    "HELP")
        isl_help_print
        exit ${EXIT_CODE}
    ;;

    "VERSION")
        isl_version_print
        exit ${EXIT_CODE}
    ;;
esac



echo_error "ISL: Mode: [${MODE}]   Verbose: [${VERBOSE}]   Dry_Run: [${DRY_RUN}]   URL: [${URL}]   Image: [${IMAGE}]   Inline: [${INLINE}]   Reverse: [${REVERSE}]"



case "${MODE}" in
    "ADD")
        isl_add "${URL}"
    ;;

    "CAT")
        isl_cat "${REVERSE}"
    ;;

    "HTML-DUMP")
        isl_html_dump "${REVERSE}" "${INLINE}"
    ;;

    "TOP")
        isl_top "${IMAGE}"
    ;;
esac


exit ${EXIT_CODE}
