#!/bin/bash
set -e

# Load environment variables from .env file
if [ -f .env ]; then
  export $(grep -v '^#' .env | xargs)
fi

# Force-remove frozen-lockfile from Dockerfile (every time, just in case)
sed -i 's/bun install --frozen-lockfile/bun install/' Dockerfile 2>/dev/null || true

# If bun.lockb is missing or broken → delete it so bun install regenerates it
[ -f bun.lockb ] && ! grep -q "lockfileVersion" bun.lockb 2>/dev/null && rm -f bun.lockb

echo "Building your site (this will work now)..."
docker build --target builder --no-cache -t own-site-builder \
  --build-arg VITE_GPT_OSS_API_KEY="${VITE_GPT_OSS_API_KEY}" .

echo "Deploying fresh build..."
docker create --name tmp-deploy own-site-builder

rm -rf ~/caddy/site/jory/*
mkdir -p ~/caddy/site/jory
docker cp tmp-deploy:/app/dist/. ~/caddy/site/jory/

# Favicon – guaranteed
cp -f favicon.gif ~/caddy/site/jory/ 2>/dev/null || echo "No favicon.gif – skipped"

# Cleanup
docker rm tmp-deploy
docker rmi own-site-builder

# Restart Caddy
docker restart caddy

echo ""
echo "DEPLOYED 100% SUCCESSFULLY"
echo "Site + favicon live now"
