#!/usr/bin/env bash
# Capstone 1, core service: shell, Git, Python, HTTP, tests, logs.
# Copies the orders service into ~/labs/capstones/core, puts it under Git, runs its tests,
# and starts it in the background on port 18081 with its JSON logs in service.log.
source "$(dirname "$0")/../lib.sh"
need git python3 curl jq
work core
PORT="${PORT:-18081}"
port_free "$PORT"

say "1. Copy the service and put it under Git (a lab-only Git identity, your real config is untouched)"
cp "$APP_SRC/orders.py" "$APP_SRC/test_orders.py" "$WORK/"
cd "$WORK"
printf '__pycache__/\n*.log\n*.pid\n' > .gitignore
export GIT_CONFIG_GLOBAL="$WORK/.gitconfig-lab"
git config --global user.name "Capstone Lab"; git config --global user.email "lab@example.com"; git config --global init.defaultBranch main
[ -d .git ] || git init -q
git add . && git commit -q -m "orders service: first version" && git log --oneline | head -1

say "2. Run the tests before running the service"
python3 -m unittest test_orders.py 2>&1 | tail -3

say "3. Start the service in the background"
PORT="$PORT" VERSION=1.0.0 nohup python3 orders.py > service.log 2>&1 &
echo $! > service.pid
wait_for "http://127.0.0.1:$PORT/readyz" 20 && echo "  orders is ready on http://127.0.0.1:$PORT (pid $(cat service.pid))"
