#!/usr/bin/env bash
set -euo pipefail

# Simple installer: build binaries to PREFIX/bin, then replace templates/ and static/
# Usage: scripts/install.sh [PREFIX]

PREFIX=${1:-/opt/weatherstation}
ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)

echo "=> Install prefix: $PREFIX"
mkdir -p "$PREFIX/bin"

# Build binaries
echo "=> Building services"
GO111MODULE=on go build -o "$PREFIX/bin/service-api"       "$ROOT_DIR/cmd/service-api"
GO111MODULE=on go build -o "$PREFIX/bin/service-forecast"  "$ROOT_DIR/cmd/service-forecast"
GO111MODULE=on go build -o "$PREFIX/bin/service-fusion"    "$ROOT_DIR/cmd/service-fusion"
GO111MODULE=on go build -o "$PREFIX/bin/service-radar"     "$ROOT_DIR/cmd/service-radar"
GO111MODULE=on go build -o "$PREFIX/bin/service-exporter"  "$ROOT_DIR/cmd/service-exporter"
GO111MODULE=on go build -o "$PREFIX/bin/service-udp"       "$ROOT_DIR/cmd/service-udp"

# Replace assets
echo "=> Replacing templates/ and static/"
rm -rf "$PREFIX/templates" "$PREFIX/static"
mkdir -p "$PREFIX/templates" "$PREFIX/static"
cp -r "$ROOT_DIR/templates/." "$PREFIX/templates/"
cp -r "$ROOT_DIR/static/."    "$PREFIX/static/"

# Optional UI bundle
if [[ -d "$ROOT_DIR/core/frontend/dist/ui" ]]; then
  echo "=> Updating UI bundle"
  rm -rf "$PREFIX/core/frontend/dist/ui"
  mkdir -p "$PREFIX/core/frontend/dist/ui"
  cp -r "$ROOT_DIR/core/frontend/dist/ui/." "$PREFIX/core/frontend/dist/ui/"
fi

echo "=> Done"
