#!/usr/bin/env bash

set -eo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/world_server_force_changed.conf"

cron_file="$CRON_FORCE_CHANGED_FILE"
notify_script="$NOTIFY_FORCE_CHANGED_SCRIPT"
log_file="$NOTIFY_FORCE_CHANGED_LOG_FILE"
lock_file="$NOTIFY_FORCE_CHANGED_LOCK_FILE"
max_log_size="$NOTIFY_FORCE_CHANGED_MAX_LOG_SIZE"

rotate_log_if_needed() {
    if [[ -f "$log_file" ]]; then
        local log_size
        log_size=$(wc -c < "$log_file")
        if (( log_size >= max_log_size )); then
            mv "$log_file" "${log_file}.$(date '+%Y%m%d_%H%M%S')"
        fi
    fi
}

log() {
    rotate_log_if_needed
    printf '[%s] %s\n' "$(date '+%F %T')" "$*" >> "$log_file"
}

exec 9>"$lock_file"

if ! flock -n 9; then
    log "another instance is still running, skip this round"
    exit 0
fi

if [[ ! -f "$cron_file" ]]; then
    log "cron file not found: $cron_file"
    exit 0
fi

target_unixtime="$(tr -d '[:space:]' < "$cron_file")"

if [[ -z "$target_unixtime" ]]; then
    log "cron file is empty: $cron_file"
    exit 0
fi

if ! [[ "$target_unixtime" =~ ^[0-9]+$ ]]; then
    log "invalid unixtime in $cron_file: $target_unixtime"
    exit 1
fi

now_unixtime="$(date +%s)"

if (( now_unixtime < target_unixtime )); then
    log "not yet reached target time: now=$now_unixtime target=$target_unixtime"
    exit 0
fi

log "target time reached: now=$now_unixtime target=$target_unixtime"
log "start notify script: $notify_script --allws"

if "$notify_script" --allws >> "$log_file" 2>&1; then
    log "notify script completed successfully"
    rm -f "$cron_file"
    log "removed cron file: $cron_file"
else
    rc=$?
    log "notify script failed with rc=$rc"
    exit "$rc"
fi
