#!/bin/bash

# Title......: now
# Description: Simple Organizer
# Author.....: Mitchell Johnston - uid 0
# Contact....: mitch@crn.hopto.org
# Updated....: Wed Jun 24 06:34:21 AM CDT 2026
#----------------------------------

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

: ' Changes:
Tue Jun 23 2026 Went back to basic calendar
Wed May 20 2026 Added wttr full weather report
Wed May 20 2026 Fixed formating of wether forcast from ansiweather
'

# 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)

# WTTR_PARAMS is space-separated URL parameters, many of which are single character s that can be lumped together. For example, "F q m" behaves the same as "Fqm".
if [[ -z "$WTTR_PARAMS" ]]; then
  # Form localized URL parameters for curl
  if [[ -t 1 ]] && [[ "$(tput cols)" -lt 125 ]]; then
      WTTR_PARAMS+='n'
  fi 2> /dev/null
  for _token in $( locale LC_MEASUREMENT ); do
    case $_token in
      1) WTTR_PARAMS+='m' ;;
      2) WTTR_PARAMS+='u' ;;
    esac
  done 2> /dev/null
  unset _token
  export WTTR_PARAMS
fi

# 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 + 1 ))

    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
}

wttr(){ ## full report
  local location="${1// /+}"
  command shift
  local args=""
  for p in $WTTR_PARAMS "$@"; do
    args+=" --data-urlencode $p "
  done
  curl -fGsS -H "Accept-Language: ${LANG%_*}" $args --compressed "wttr.in/${location}"
}


# 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
-w            Wttr full display 

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 "$(wclock)  πŸ”— ${BY}$(grep -cE 'http|https' "$TASKS")${N} βœ”  ${BY}$(grep -cE '^\-' "$TASKS")${N}"
        ;;
    -w) # wttr
        wttr
        ;;
    *) # 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 ***
        hclock -
        echo -e "\b$(cat /tmp/mw.out| sed 's/^.*L/L/g') | 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 ""
        echo "πŸ“… ${BLD}$(date "+%A %B %d, %Y")${N}"
        calendar -A 3 | sed -e 's/\*//g' -e "s/$(date "+%b %d")/${BG}Today${N}/g"
        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}
        fi
        LINKS=$(grep -cE 'http|https' "$TASKS")
        if [ $LINKS -gt 0 ]
        then
            echo "πŸ”— ${BY}Links: ${BC}$LINKS${N}"
            echo " "
        fi
esac


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

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

# vim: nospell ft=sh