#!/bin/bash

# Title......: now
# Description: Simple Organizer
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Wed May 20 06:28:11 AM CDT 2026
#----------------------------------

# Sections: Changes variables functions setup main 
# use '#' in vi/vim to jump to word under cursor

: ' Changes:
Wed May 20 2026 Changes calender source from file to output of calendar
Wed May 20 2026 Fixed formating of wether forcast from ansiweather
Tue May 19 2026 Fixed calendar forat to tab seperated
Tue May 19 2026 Rewrite and changed name to 'now'
Sun May 17 2026 Added -F to display defined functions
Thu Apr 09 2026 Added -C to display all entries
Sat Jan 17 2026 Added clock-emoji
Fri Jan 16 2026 Removed 'now'
Thu Oct 23 2025 Added URL management
Thu May 22 2025 Added more emoji for tasks
Sat Feb 15 2025 Moved this from .bashrc
'

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
[ "$DEBUG" == 1 ] && echo "---Variables---" && set -x
PS4='$SECONDS $LINENO: '                   # debug prompt
DOW=$(date +%a)                            # day of week: Thu
TODAY=$(date +%m/%d)                       # month/day: 03/25
DOM=$(date +%d)                            # day of month: 25
OS=$(uname -s)                             # OS type: SunOS Linux
NAME=${0##*/}                              # name of the script
DIR="$(basename $PWD)"                     # location started
PDIR="$(cd ..;basename $PWD)"              # parrent dir
TASKS="/home/mitch/etc/tasks.md"                     # location of task file
PATH="$PATH:~/bin"
CAL_FILE="/home/mitch/.calendar/calendar"  # Define the calendar file path

#
# The default time output uses emoji numbers, if passed -time it won't.
# This is due to some terminal not displaying them correctly. 
#
if [[ "$1" = "-time" ]] 
then
    TIME=$(etime -)
    shift
else
    TIME=$(etime)
fi

# Get current date info
CURRENT_MONTH=$(date +%m)
CURRENT_YEAR=$(date +%Y)
TODAY_EPOCH=$(date -d "today" +%s)


# Colors - uncomment if needed
R=$(tput setaf 1)                          # red
BR=$(tput setaf 1; tput bold)              # bold red
G=$(tput setaf 2)                          # green
BG=$(tput setaf 2; tput bold)              # bold green
Y=$(tput setaf 3)                          # yellow
BY=$(tput setaf 3; tput bold)              # bold yellow
B=$(tput setaf 4)                          # blue
BM=$(tput setaf 5; tput bold)              # bold magenta
BC=$(tput setaf 6; tput bold)              # bold cyan
C=$(tput setaf 6)                          # cyan
BL=$(tput setaf 7; tput bold)              # bold light grey
BLD=$(tput bold)                           # bold
N=$(tput sgr0)                             # normal
SIT=$(tput sitm)                           # italics
RIT=$(tput ritm)                           # remove italics
UL=$(tput smul)                            # turn underline on
NL=$(tput rmul)                            # turn underline off
RV=$(tput rev)                             # turn on reverse mode
ROWS=$(tput lines)
COLS=$(tput cols)
[ "$DEBUG" == 1 ] && set +x && read -p "${N}-Continue-" -n 1 x

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

bl(){ ## write a blank line
	# Use: bl
	[ "$DEBUG" == "1" ] && set -x
    echo ""
}

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

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

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" "$*"
}

moon_phase() {
    # Reference date: New Moon on Jan 7, 1970 (Unix timestamp 592500)
    local reference=592500
    local period=2551443 # Lunar cycle in seconds (29.53 days)

    local now=$(date +%s)
    local diff=$((now - reference))
    local phase=$((diff % period))
    local percent=$((phase * 100 / period))

    # Array of moon emojis corresponding to the cycle
    local moons=(🌑 🌒 🌓 🌔 🌕 🌖 🌗 🌘)
    local index=$((percent * 8 / 100))

    # Ensure index stays within bounds
    if [ $index -ge 8 ]; then
        index=0
    fi

    echo "${moons[index]}"
}

days_until(){ ## display days until event
    # 1. Convert target date (argument $1) to seconds since epoch
    local target_epoch
    target_epoch=$(date -d "$1" +%s) || return 1

    # 2. Get current time in seconds since epoch
    local current_epoch
    current_epoch=$(date +%s)

    # 3. Calculate difference in seconds
    local diff_seconds=$(( target_epoch - current_epoch ))

    # 4. Convert seconds to days (86400 seconds in a day)
    local diff_days=$(( diff_seconds / 86400 ))

    if [ "$diff_days" -lt 0 ]; then
        echo "The date $1 has already passed ($(( -diff_days )) days ago)."
    else
        echo "${2}There are ${BR}$diff_days${N} days until ${SIT}$1${RIT}."
    fi
}

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

# part of my code management system
# if you want a function or peice of code from another script:
#  !!{script} -F {function}
#  will insert the code.
[[ "$1" = "-V" ]] && bat -p -l bash $0 && exit
if [[ "$1" = "-F" ]] 
    then
        [[ "$#" -eq 2 ]] && declare -f "$2" |bat -p -l bash && exit
        [[ "$#" -eq 1 ]] && declare -f |bat -p -l bash && exit
fi

# 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
	exit
fi

# display help if needed
if [ "$1" == "-h" ] || [ "$1" == "--help" ]
then
fmt -s -w $(tput cols) <<END
${BG}$NAME${N}

Displays calender, tasks, and urls to look at.

${BC}Options${N}

{default}     Shows everything
-c            Edit ~/.calendar
-C            Display ~/.calendar
-l            List saved links, prompts to rm them
-o            Open saved links, prompts to rm them
-e            Edit $TASKS
-s            Display one line status
-t {string}   Adds entry to task list

URL key words:${BY} check, read, watch, dl${N}

# alias task='$NAME -t' in ~/.bashrc

i.e.

task "take out trash"
task read http://crn.hopto.org/bible/

END
exit
fi

# listing of required apps
command -v bash >/dev/null || sudo apt install bash -qyy

# main
#--------------------------- 
[ "$DEBUG" == 1 ] && echo "---Functions---" && typeset -F && read -p "${N}-Continue-" -n 1 x
[ "$DEBUG" == 1 ] && echo "---Main---" && set -x


# Use: today  {-c to edit calendar file}

case "$1" in
    -c) # edit calendar
        vim ~/.calendar/calendar
        SHOW=y
        today
        ;;
    -C) # display full calendar
        egrep -v '^#' ~/.calendar/calendar |sed -e 's/Passed/⚰️/1' -e 's/call/📞/1' -e 's/vacation/🚙/1' -e 's/birthday/🎂/1' -e 's/anniversary/💍/1'
        ;;
    -l) # list links
        \grep -iE 'http|https' "$TASKS" |sed -e 's/^check/🔍/1' -e 's/^read/👓/1' -e 's/^watch/🎬/1' -e 's/^dl/⬇️/1' -e 's/^pipe/🤓/1' -e 's/^food/🍲/1'
        [ "$(grep -c http $TASKS)" -gt 0 ] && read -p "Remove them? " -n 1 ANS
        [ "$ANS" == "y" ] && sed -i '/http/d' $TASKS
        echo ' '
        ;;
    -o) # open links links and rm them when done
        for URL in $(grep -iE 'http|https' $TASKS | awk '{print $NF}')
        do
            (xdg-open "$URL" >/dev/null 2>&1) 
        done
        sed -i '/http/d' $TASKS 2>/dev/null
        echo ' '
        ;;
    -t) # task or URL entry
        if [[ "$*" == *"http"* ]]
        then
            shift
            echo "$*" >>$TASKS
        else
            shift
            echo "- [ ] $*" >>$TASKS
        fi
        log "New task: $*"
        SHOW=y
        ;;
    -e) # edit task list
        vim $TASKS
        SHOW=y
        ;;
    -s) # status display
        echo "${BG}$(fclock)${N}  🔗 ${BY}$(grep -cE 'http|https' "$TASKS")${N} ✔  ${BY}$(grep -cE '^\-' "$TASKS")${N}"
        ;;
    *) # normal display
        clear
        # /tmp/mw.out created by:
        # curl -s -o /tmp/mw.out https://wttr.in/?format=4 >/dev/null 2>&1
        # /tmp/fc.out created by:
        #  ansiweather -f 3 | sed  -e 's/^.*L/L/1' -e 's/:/\n/1' -e 's/[-]/\n/g' >/tmp/fc.out
        #  *** Both in crontab ***
        echo "$TIME |$(cat /tmp/mw.out) | MP $(moon_phase)"
        [[ "$(hostname)" = "mitch-laptop" ]] && ssh mitch-crn -q -t /home/mitch/bin/status
        echo ""
        cat /tmp/fc.out | sed 's/^[[:space:]]//g'
        echo ""
        #--- Begin calendar parse ---
        # Read the file line by line
        calendar | sed -e 's/\*//g' -e 's# #/#1' -e "s/$(date +%b)/$(date +%m)/g" >/tmp/cal.out
        while read -r line || [[ -n "$line" ]]; do
            # Extract date and description (assuming format MM/DD Description)
            event_date_raw=$(echo "$line" | awk '{print $1}')
            description=$(echo "$line" | cut -d$'\t' -f2-)

            # Parse month and day from the event date
            event_month=$(echo "$event_date_raw" | cut -d'/' -f1)
            event_day=$(echo "$event_date_raw" | cut -d'/' -f2)

            # Only process events for the current month
            if [[ "$event_month" == "$CURRENT_MONTH" ]]; then
                # Create full date string for comparison
                event_full_date="$CURRENT_YEAR-$event_month-$event_day"
                EVENT_EPOCH=$(date -d "$event_full_date" +%s)

            # Calculate difference in days
            diff_seconds=$((EVENT_EPOCH - TODAY_EPOCH))
            diff_days=$(( (diff_seconds + 43200) / 86400 )) # Rounding to nearest day

            if [ "$diff_days" -lt 0 ]; then
                echo "[PAST] $event_date_raw: $description"
            elif [ "$diff_days" -eq 0 ]; then
                echo "${BG}[TODAY] $event_date_raw: $description${N}"
            else
                echo "In ${BLD}$diff_days days${N}: $event_date_raw - ${BC}$description${N}"|sed -E -e 's/Passed/⚰️/1'  -e 's/[Cc]all/📞/1' -e 's/([tT]ake|[pP]ickup)/🚙/1' -e 's/[Bb]irthday/🎂/1' -e 's/[Aa]nniversary/💍/1'
            fi
            fi
		done < /tmp/cal.out
            #-------- End calendar parse ----
            echo ""
            if [ $(grep -cE '^-' "$TASKS") -gt 0 ]
            then
                echo -n "✔  ${BC}Tasks:${N}"
                cat $TASKS|grep -vE 'URL|Enter:|http|https' >/tmp/$$.md
                sed  -e 's/[aA]ppointment/⏰ /1' -e 's/[cC]all/☎️ /1' -e 's/[hH]ouse/🏡 /1' -e 's/[cC]ar\ /🚙/1' -e 's/[wW]eb\ /🕸️ /1'  -e 's/[pP]rep /🏹 /1' /tmp/$$.md | bat -l markdown -p
                echo ${N}
            else
                ~/bin/quote
            fi
            LINKS=$(grep -cE 'http|https' "$TASKS")
            if [ $LINKS -gt 0 ]
            then
                echo "🔗 ${BY}Links: ${BC}$LINKS${N}"
                echo -n "$UL"
            fi
            # Countdown to any special day(s)
            days_until "June 12" "🥳"
            days_until "June 30" "👣"
esac


[ "$SHOW" == "y" ] && $0 || exit 0

# Code snippets
#--------------------------- 

# vim: nospell ft=sh
