FROM alpine:latest

RUN apk add --no-cache curl jq bash

ENV GITHUB_REPO="" \
    GITEA_URL="" \
    GITEA_REPO="" \
    PB_TOKEN="" \
    PB_TITLE="" \
    PB_MSG=""

RUN echo '#!/bin/bash' > /script.sh && \
    echo 'GITHUB_VERSION=$(curl -s "https://api.github.com/repos/${GITHUB_REPO}/releases/latest" | jq -r ".tag_name")' >> /script.sh && \
    echo 'GITEA_VERSION=$(curl -s "${GITEA_URL}/api/v1/repos/${GITEA_REPO}/releases/latest" -H "accept: application/json" | jq -r ".tag_name")' >> /script.sh && \
    echo 'echo "GitHub Latest Version: ${GITHUB_VERSION}"' >> /script.sh && \
    echo 'echo "Gitea Latest Version: ${GITEA_VERSION}"' >> /script.sh && \
    echo 'if [ "$(printf "%s\n" "${GITEA_VERSION}" "${GITHUB_VERSION}" | sort -V | head -n1)" = "${GITHUB_VERSION}" ]; then' >> /script.sh && \
    echo '  echo "❌❌GitHub release is older or the same. Stopping workflow.❌❌"' >> /script.sh && \
    echo '  curl --silent --output /dev/null -u "${PB_TOKEN}:" -X POST https://api.pushbullet.com/v2/pushes --header "Content-Type: application/json" --data-binary "{\"type\": \"note\", \"title\": \"${PB_TITLE}\", \"body\": \"${PB_MSG} ${GITHUB_VERSION}\" }"' >> /script.sh && \
    echo 'else' >> /script.sh && \
    echo '  echo "✅✅GitHub release is newer. Continuing workflow.✅✅"' >> /script.sh && \
    echo '  curl --silent --output /dev/null -u "${PB_TOKEN}:" -X POST https://api.pushbullet.com/v2/pushes --header "Content-Type: application/json" --data-binary "{\"type\": \"note\", \"title\": \"${PB_TITLE}\", \"body\": \"${PB_MSG} ${GITHUB_VERSION}\" }"' >> /script.sh && \
    echo 'fi' >> /script.sh && \
    chmod +x /script.sh

CMD ["/script.sh"]