#!/bin/bash

TODATE=$(date +"%Y-%m-%d" -d 'now')
THISYEAR=$(date +"%Y" -d 'now')
THISMONTH=$(date +"%m" -d 'now')
# DAY 31st will meet errors
#NEXTMONTH=$(date +'%m' -d 'next month')
#NEXTMONTH=$(date -d "-$(date +%d) days +2 month" +%m)
NEXTMONTH=$(date +'%m' --date="$(date +%Y-%m-15) next month")
LASTWORKINGDATE=${THISYEAR}-${THISMONTH}-$(cal ${THISMONTH} ${THISYEAR} | awk '{if(NF>1) a=$NF; if(NF==7) a=$6} END{print a}')
ROUTE="XL-ACCOUNTING"
GOOGLE_CHAT_WEBHOOK_URL_ACCOUNTING="https://chat.googleapis.com/v1/spaces/AAAAyt3toes/messages?key=AIzaSyDdI0hCZtE6vySjMm-WEfRq3CPzqKqqsHI&token=nKk_hxnWdahMmem44ovvDK3SgFRAExHSWbM3v7CMrCM%3D"

if [ "${TODATE}" == "${LASTWORKINGDATE}" ]; then
        MESSAGE=$(printf "[貼心提醒]\n${NEXTMONTH} 月即將來臨, 麻煩各個版本的負責人, 請協助填寫 ${THISYEAR}-${THISMONTH} 月的永久性\n謝謝大家的配合, 麻煩了!")
        echo ${MESSAGE}
        curl -sS -X POST --data-urlencod "message=${MESSAGE}" "https://web-dev.x-legend.com/api/${ROUTE}/"

        # 送出資訊給 Google Chat Webhook
        curl -sS -X POST -H 'Content-Type: application/json' $GOOGLE_CHAT_WEBHOOK_URL_ACCOUNTING -d "{\"text\": \"${MESSAGE}\"}"
fi
