#!/usr/bin/env bash
# install.sh — Install the El SDK from the latest Gitea release.
#
# Usage:
#   bash install.sh
#   EL_VERSION=v1.0.0   bash install.sh     # pin a specific release tag
#   EL_PREFIX=/opt/el   bash install.sh     # custom install prefix
#
# Environment variables:
#   EL_VERSION   Release tag to download (default: latest)
#   EL_PREFIX    Install prefix           (default: /usr/local)

set -euo pipefail

REPO_BASE="https://git.neuralplatform.ai/neuron-technologies/el"
VERSION="${EL_VERSION:-latest}"
PREFIX="${EL_PREFIX:-/usr/local}"

BIN_DIR="${PREFIX}/bin"
LIB_DIR="${PREFIX}/lib/el"

RELEASE_BASE="${REPO_BASE}/releases/download/${VERSION}"

echo "==> Installing El SDK ${VERSION}"
echo "    prefix : ${PREFIX}"
echo "    bin    : ${BIN_DIR}"
echo "    lib    : ${LIB_DIR}"
echo

# Create directories
mkdir -p "${BIN_DIR}" "${LIB_DIR}"

# Download helper
download() {
    local url="$1"
    local dest="$2"
    echo "    Downloading $(basename "${dest}")..."
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "${url}" -o "${dest}"
    elif command -v wget >/dev/null 2>&1; then
        wget -q "${url}" -O "${dest}"
    else
        echo "Error: neither curl nor wget found" >&2
        exit 1
    fi
}

# Download assets
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

download "${RELEASE_BASE}/elc"          "${TMP_DIR}/elc"
download "${RELEASE_BASE}/el_runtime.c" "${TMP_DIR}/el_runtime.c"
download "${RELEASE_BASE}/el_runtime.h" "${TMP_DIR}/el_runtime.h"

# Install
install -m 755 "${TMP_DIR}/elc"          "${BIN_DIR}/elc"
install -m 644 "${TMP_DIR}/el_runtime.c" "${LIB_DIR}/el_runtime.c"
install -m 644 "${TMP_DIR}/el_runtime.h" "${LIB_DIR}/el_runtime.h"

echo
echo "==> El SDK installed successfully"
echo
echo "    elc binary : ${BIN_DIR}/elc"
echo "    runtime    : ${LIB_DIR}/el_runtime.c"
echo "    header     : ${LIB_DIR}/el_runtime.h"
echo
echo "Add the following to your Makefile to build El programs:"
echo
echo "    EL_LIB := ${LIB_DIR}"
echo "    ELC    := elc"
echo "    CC     := cc"
echo "    CFLAGS := -std=c11 -O2 -I\$(EL_LIB)"
echo
echo "    dist/myapp.c: src/myapp.el"
echo "    \t\$(ELC) src/myapp.el > dist/myapp.c"
echo
echo "    dist/myapp: dist/myapp.c"
echo "    \t\$(CC) \$(CFLAGS) -o dist/myapp dist/myapp.c \$(EL_LIB)/el_runtime.c -lcurl -lpthread"
echo
