#! /bin/bash . /usr/src/m2/framework/bash_functions.sh cron="/etc/cron.d/m2_rates_effective_from_cache_automatic_cron" thingy="/usr/local/m2/m2_rates_effective_from_cache" today=$(date +'%Y-%m-%d') tomorrow=$(date -I -d "$today + 1 days") cache_check_hour='03' date_start=$(date +'%Y-%m-%d %H:%M:00') hour_before=$(date -d '1 hour ago' "+%Y-%m-%d %H:%M:00") date_end="${tomorrow} 23:59:59" #basic validation date_regex="^2[0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$" declare -A dates set_database_variables ceil_date() { # ugly af local full_date="$1" local seconds="$(echo "$full_date" | awk -F: '{print $3}')" local ceiled_date=0 local remaining_seconds=0 if [[ $seconds != "00" ]]; then remaining_seconds=$((60 - seconds)) if ! ceiled_date=$(date -d @$(( $(date -d "$full_date" +%s) + remaining_seconds)) '+%Y-%m-%d %T'); then echo "Error while generating ceiled date. Check error message above" return 1 fi else ceiled_date="$full_date" fi echo "$ceiled_date" return 0 } create_cron_from_date() { if [[ ${dates["$1"]} == 1 ]]; then return 0 fi dates["$1"]=1 local cron_date="$1" local prefix="$2" local tariff_id="$3" local minute=$(date -d "$cron_date" +%M) local hour=$(date -d "$cron_date" +%H) local month=$(date -d "$cron_date" +%m) local day=$(date -d "$cron_date" +%d) printf "%s %s %s %s * root $thingy -d '$cron_date'\n" "${minute##0}" "${hour##0}" "${day##0}" "${month##0}" >> $cron } rm -f "$cron"; touch $cron; echo "# This cron has been created automatically by $(basename "$0") at $(date_time). Do NOT edit it manually" >> $cron echo "Checking last hour cache" # Check last hour cache $thingy -r "$hour_before" "$date_start" echo "Done" while read -r effective_from; do if [[ ! $effective_from =~ $date_regex ]]; then echo "Got bad date $effective_from. Skipping this one" continue fi if ! ceiled_effective_from=$(ceil_date "$effective_from"); then continue fi create_cron_from_date "$ceiled_effective_from" done < <(MYSQL_PWD="$DB_PASSWORD" /usr/bin/mysql -h "$DB_HOST" -u "$DB_USERNAME" "$DB_NAME" -sNe "SELECT effective_from FROM rates where effective_from BETWEEN '$date_start' AND '$date_end' GROUP BY effective_from") hour=$(date -d "$date_start" +%H) if [[ $hour == $cache_check_hour ]]; then echo "Checking last day cache" day=$(date -d "1 day ago" +%d) period_end=$(date -d "$date_start" "+%Y-%m-$day 23:59:00") period_start=$(date -d "$date_start" "+%Y-%m-$day 00:00:00") $thingy -c "$period_start" "$period_end" echo "Done" fi chmod 0644 $cron && /sbin/service crond restart > /dev/null