#!/usr/bin/env zsh

# Checks for custom FileWave scheduled tasks that reference settings removed in
# FileWave 16.3. This validates only this known upgrade blocker.

custom_file="${1:-/usr/local/filewave/django/filewave/settings_custom.py}"

if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  YELLOW='\033[1;33m'
  BLUE='\033[0;34m'
  NC='\033[0m'
else
  RED=''
  GREEN=''
  YELLOW=''
  BLUE=''
  NC=''
fi

active_count=0
commented_count=0
line_number=0

pass() {
  printf "%bPASS%b: %s\n" "$GREEN" "$NC" "$1"
}

warn() {
  printf "%bWARNING%b: %s\n" "$YELLOW" "$NC" "$1"
}

fail() {
  printf "%bFAIL%b: %s\n" "$RED" "$NC" "$1"
}

info() {
  printf "%bINFO%b: %s\n" "$BLUE" "$NC" "$1"
}

line_has_removed_setting() {
  local line="$1"
  [[ "$line" == *"settings.DAILY_SCHEDULE"* || "$line" == *"settings.HOURLY_SCHEDULE"* ]]
}

printf "Checking FileWave custom settings for removed 16.3 scheduled task settings.\n"
printf "File: %s\n\n" "$custom_file"

if [[ ! -e "$custom_file" ]]; then
  fail "Settings file was not found. Run this on the FileWave Server, or pass the settings_custom.py path as the first argument."
  exit 2
fi

if [[ ! -r "$custom_file" ]]; then
  fail "Settings file exists but is not readable. Re-run with an account that can read the file, for example with sudo."
  exit 2
fi

while IFS= read -r line || [[ -n "$line" ]]; do
  (( line_number++ ))
  active_part="${line%%#*}"

  if line_has_removed_setting "$active_part"; then
    (( active_count++ ))
    fail "Line $line_number is active: $line"
    continue
  fi

  if ! line_has_removed_setting "$line"; then
    continue
  fi

  (( commented_count++ ))
  warn "Line $line_number has only a commented reference: $line"
done < "$custom_file"

printf "\n"

if (( active_count == 0 && commented_count == 0 )); then
  pass "No references to settings.DAILY_SCHEDULE or settings.HOURLY_SCHEDULE were found."
  info "This server is clear for this known FileWave 16.3 upgrade blocker. Continue with normal FileWave upgrade prerequisites."
  exit 0
fi

if (( active_count > 0 )); then
  fail "$active_count active reference(s) to removed scheduled task settings were found."
  printf "\nDO NOT RUN THE FILEWAVE 16.3 UPGRADE UNTIL THESE ENTRIES ARE ADDRESSED.\n"
  printf "Remove the custom scheduled task entries, or comment them out temporarily, then re-run this script.\n"
  printf "Affected file: %s\n" "$custom_file"
  exit 1
fi

warn "$commented_count commented reference(s) to removed scheduled task settings were found."
info "Commented references should not block the upgrade, but removing stale commented lines is recommended."
info "No active references were found for this known FileWave 16.3 upgrade blocker."
exit 0
