#!/bin/bash

set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
ARCH=$(uname -m)
TEMP_DIR="${SCRIPT_DIR}/temp"
SOS="${TEMP_DIR}/sos"
PROJECT="$(basename "${SCRIPT_DIR}")"

echo "Publishing simple-object-server to gitea.jde.nz/public/simple-object-server:latest"

function die() {
    title "error: $1"
    exit 1
}

[[ -n $SOS_WRITE_TOKEN ]] || die "SOS_WRITE_TOKEN not specified"

# clear output dir
rm -rf "${SCRIPT_DIR}/output" 
mkdir -p "${SCRIPT_DIR}/output"

# build release version
export CMAKE_BUILD_TYPE="Release"
"${SCRIPT_DIR}/build.sh"

[ -f "${SCRIPT_DIR}/output/simple-object-server" ] || die "Build failed."
[ -f "${SCRIPT_DIR}/output/hash_token" ] || die "hash_token utility not found in build output."

# download the sos binary
mkdir -p "${TEMP_DIR}"
trap 'rm -rf "${TEMP_DIR}"' EXIT
curl -L -o "${SOS}" "https://getbin.xyz/sos"
chmod +x "${SOS}"

# upload arch-specific binary
"${SOS}" upload "getbin.xyz" "${SCRIPT_DIR}/output/${PROJECT}" "${PROJECT}:latest-${ARCH}"

# upload arch-specific hash_token utility
"${SOS}" upload "getbin.xyz" "${SCRIPT_DIR}/output/hash_token" "sos-hash:latest-${ARCH}"

# upload generic install script (ok if multiple times as we iterate through arch's)
"${SOS}" upload "getbin.xyz" "${SCRIPT_DIR}/install.sh" "simple-object-server-install:latest"

# create and upload the arch-specific docker image
IMAGE_NAME="gitea.jde.nz/public/simple-object-server:latest-${ARCH}"
docker build \
    -f "${SCRIPT_DIR}/Dockerfile.sos" \
    -t "${IMAGE_NAME}" \
    "${SCRIPT_DIR}"

docker push "${IMAGE_NAME}"
