#!/bin/sh

start_hourly_bell(){
  # Set up an array of message templates
  messages=(
    "In the silent depths of the night, a bell tolls and tells you it is %s o'clock."
    "A lone bell tolls, a reminder of the hour %s."
    "On the top of the hill, the ancient bell tolls to mark the hour, %s."
    "Deep in the forest, the bell echoes announcing it's %s o'clock."
    "You hear the chimes of a far-off bell. It's the hour of %s."
    "From the cathedral tower, the bell tolls out the hour of %s."
    "The bell of the clock tower tolls %s o'clock."
    "A bell tolls in the distance, signaling that it is %s."
    "On a still night, the bell tolls, %s o'clock."
    "As you sit in your quiet study, a bell tolls, announcing the hour %s."
    "A bell tolls, and the hour is %s"
    "The bell tolls, and you realize it's %s o'clock."
    "A bell echoes in the valley, announcing the hour %s."
    "With a final toll, the bell signals the hour %s."
    "A bell tolls softly, reminding you that it is %s o'clock."
  )

  while true; do
      current_time=$(date +%T) # gets the current hour and minutes
      current_hour=$(date +%H) # gets the current hour in 24 hour format
      current_minutes=$(date +%M) # gets the current minute
      # calculate how many seconds are left until the next hour
      sleep_time=$((3600 - (current_minutes * 60) - $(date +%S))) 
      sleep $sleep_time
      # Choose a random message template
      message=${messages[$RANDOM % ${#messages[@]}]}
      # Use the bg_log function to output the message
      bg_log "$(printf "$message" "$current_hour")"
  done
}

install_hourly_bell(){
  if grep -q "source ${BASH_SOURCE[0]}" ~/.bashrc; then
    echo "You have already memorized this spell"
  else
    echo "Do you wish to memorize this spell? (yes/no)"
    read -r answer
    if [ "$answer" == "yes" ]; then
      echo "source ${BASH_SOURCE[0]}" >> ~/.bashrc
      echo "Spell memorized in .bashrc, so the bell will always be active in the terminal."
    else
      echo "The bell will only ring in this shell window."
    fi
  fi
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    install_hourly_bell
    trap '' 2  # Traps the INT signal and does nothing with it
    start_hourly_bell &  # runs the function in background
    echo "Hourly bell has started" # message when script is run
fi