#! /bin/bash
# Builds the current code as the specified version, and uploads it to the server.
set -euo pipefail

if [[ ! -f .env.local ]]; then
    echo 'VOXELVERSE_SSH_ADDR="user@server.com"' > .env.local
    echo "❌ .env.local did not exist; it was now created, please fill it in."
    exit 1
fi

. .env.local

scripts/release.sh "$@"
VERSION="$1"

echo "==> Uploading to the server..."
ssh $VOXELVERSE_SSH_ADDR "mkdir -p ~/www/share/voxelverse/versions/$VERSION"

echo "==> Creating a CAS patch..."
mkdir release/cas
scripts/cas-write.sh release/cas assets release/assets-$VERSION.idx
(cd release/cas && zip -r ../cas-patch.zip *)

echo "==> Uploading files to server..."
ssh $VOXELVERSE_SSH_ADDR "[[ -e ~/www/share/voxelverse/versions/$VERSION/bins-linux-$VERSION.zip ]]" \
  && { echo "❌ Bins package already exists on remote! Aborting."; exit 1; }

scp release/bins-linux-$VERSION.zip $VOXELVERSE_SSH_ADDR:~/www/share/voxelverse/versions/$VERSION/
scp release/assets-$VERSION.idx $VOXELVERSE_SSH_ADDR:~/www/share/voxelverse/versions/$VERSION/
scp release/cas-patch.zip $VOXELVERSE_SSH_ADDR:~/www/share/voxelverse/assets/

echo "==> Applying CAS patch on remote..."
ssh $VOXELVERSE_SSH_ADDR "cd ~/www/share/voxelverse/assets && unzip -o cas-patch.zip && rm cas-patch.zip"

echo "✅ Linux release uploaded to server"