#!/bin/sh
# ============================================================================
# KiBot Template Bootstrapping Script
# ============================================================================

set -euo pipefail

# Create the Development Branch
git checkout -qb dev
echo "Created Development Branch"

# Add the Asymworks KiCad Library
git remote --no-verbose add -f asymworks-kicad-lib https://git.asymworks.com/asymworks/kicad-library >/dev/null
git subtree -q add --prefix lib/asymworks asymworks-kicad-lib main --squash -m "[bootstrap] Add subtree 'Asymworks/KiCad-Library' at 'lib/asymworks'"
echo "Added Asymworks KiCad Library"

# Initialize the Project Metadata
PYTHON=$(which python || echo "")
if [ -z "$PYTHON" ] ; then
    PYTHON=$(which python3 || echo "")
    if [ -z "$PYTHON" ] ; then
        echo "Python interpreter not found as 'python' or 'python3'" >&2
        exit 1
    fi
fi

echo
echo "Initializing Project Metadata"
echo "-----------------------------"
${PYTHON} kibot/scripts/metadata.py init
${PYTHON} kibot/scripts/metadata.py update Asymworks_Template.kicad_pro
ASSY_NUMBER=$(${PYTHON} kibot/scripts/metadata.py print AssemblyNumber)

echo
echo "Initialized ${ASSY_NUMBER}"

# Rename the KiCad Project based on the directory name
git mv --no-verbose Asymworks_Template.kicad_dru "${ASSY_NUMBER}.kicad_dru"
git mv --no-verbose Asymworks_Template.kicad_pro "${ASSY_NUMBER}.kicad_pro"
git mv --no-verbose Asymworks_Template.kicad_sch "${ASSY_NUMBER}.kicad_sch"
git mv --no-verbose Asymworks_Template.kicad_pcb "${ASSY_NUMBER}.kicad_pcb"
echo "Renamed project to \"${ASSY_NUMBER}.kicad_pro\""

# Push the Develpment Branch to Gitea
git add --no-verbose project.json
git commit -aq -m 'Initialize Project'
git push --no-verbose -qu origin dev >/dev/null
echo "Initialized and Committed Project"

# Bootstrap Complete
echo "Bootstrap complete. Please run 'git pull' after the CI action finishes.'"
