#!/usr/bin/env bash
set -Eeuo pipefail
SRC=/tmp/ok-ithaki.apk
SUM=/tmp/ok-ithaki.apk.sha256
DST_DIR=/var/www/ok-site/downloads
DST="$DST_DIR/ok-ithaki.apk"
DST_SUM="$DST_DIR/ok-ithaki.apk.sha256"
STAMP="$(date +%Y%m%d_%H%M%S)"
BACKUP="$DST_DIR/ok-ithaki.previous.$STAMP.apk"
REPORT=/tmp/OK_ITHAKI_APK_PUBLISH_REPORT.txt
exec > >(tee "$REPORT") 2>&1

[[ -s "$SRC" ]]
[[ -s "$SUM" ]]
cd /tmp
sha256sum -c "$SUM"
mkdir -p "$DST_DIR"
if [[ -f "$DST" ]]; then cp -a "$DST" "$BACKUP"; fi
install -m 0644 "$SRC" "$DST"
install -m 0644 "$SUM" "$DST_SUM"
chown nginx:nginx "$DST" "$DST_SUM" 2>/dev/null || chown www-data:www-data "$DST" "$DST_SUM" 2>/dev/null || true
restorecon -F "$DST" "$DST_SUM" 2>/dev/null || true

EXPECTED="$(awk '{print $1}' "$SUM")"
ACTUAL="$(sha256sum "$DST" | awk '{print $1}')"
[[ "$EXPECTED" == "$ACTUAL" ]]
HTTP_CODE="$(curl -k -sS --max-time 30 --resolve www.ok-ithaki.gr:443:127.0.0.1 -o /tmp/ok-ithaki-download-test.apk -w '%{http_code}' 'https://www.ok-ithaki.gr/downloads/ok-ithaki.apk')"
[[ "$HTTP_CODE" == 200 ]]
PUBLIC_SHA="$(sha256sum /tmp/ok-ithaki-download-test.apk | awk '{print $1}')"
[[ "$PUBLIC_SHA" == "$EXPECTED" ]]

echo APK_SITE_HTTP_CODE=$HTTP_CODE
echo APK_SERVER_SHA256=$ACTUAL
echo APK_PUBLIC_SHA256=$PUBLIC_SHA
echo APK_BACKUP_PATH=$BACKUP
echo APK_DOWNLOAD_URL=https://www.ok-ithaki.gr/downloads/ok-ithaki.apk
echo APK_PUBLISH_TO_SITE=OK
