#!/bin/bash
set -e

# ============================================================
# Pharmacy System — New Customer Project Initialisation
# ============================================================
# Sets up a Bitbucket fork of the starter repo with the
# upstream-tracking branch model:
#
#   main     — production (deployed via Envoyer)
#   develop  — staging/dev (deployed via Envoyer)
#   upstream — clean tracking branch for starter updates
#
# Prerequisites:
#   1. Fork pharmacy-system-starter on Bitbucket
#   2. Clone the fork locally
#   3. Run this script from inside the cloned fork
#
# Usage:
#   cd ~/Code/pharmacy-clientname
#   ./init-customer-project.sh
#
# ============================================================

STARTER_BRANCH="master"

# --- Preflight checks ---
if [ ! -d ".git" ]; then
    echo "Error: Not a git repository."
    echo ""
    echo "Usage:"
    echo "  1. Fork pharmacy-system-starter on Bitbucket"
    echo "  2. Clone your fork:  git clone git@bitbucket.org:mtcmedia/pharmacy-clientname.git"
    echo "  3. cd into the clone: cd pharmacy-clientname"
    echo "  4. Run this script:  ./init-customer-project.sh"
    exit 1
fi

# Check origin exists (should point to the fork)
FORK_REPO=$(git remote get-url origin 2>/dev/null || true)
if [ -z "$FORK_REPO" ]; then
    echo "Error: No 'origin' remote found. Is this a cloned repository?"
    exit 1
fi

# Auto-detect SSH vs HTTPS from origin URL to use the matching protocol for the starter
if echo "$FORK_REPO" | grep -q "^https://"; then
    STARTER_REPO="https://bitbucket.org/mtcmedia/pharmacy-system-starter.git"
else
    STARTER_REPO="git@bitbucket.org:mtcmedia/pharmacy-system-starter.git"
fi

# Check we haven't already run this
if git remote get-url starter &>/dev/null; then
    echo "Error: 'starter' remote already exists. Has this script already been run?"
    exit 1
fi

if git rev-parse --verify upstream &>/dev/null; then
    echo "Error: 'upstream' branch already exists. Has this script already been run?"
    exit 1
fi

echo "============================================"
echo "  Pharmacy System — Project Initialisation"
echo "============================================"
echo ""
echo "  Fork repo:    $FORK_REPO"
echo "  Starter repo: $STARTER_REPO"
echo "  Working dir:  $(pwd)"
echo ""
read -p "Continue? (y/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    exit 1
fi

# --- Step 1: Add the starter as a remote ---
echo ""
echo "[1/6] Configuring remotes..."
git remote add starter "$STARTER_REPO"
git fetch starter

echo "  Remotes configured:"
git remote -v

# --- Step 2: Create branch structure ---
echo ""
echo "[2/6] Creating branch structure..."

# upstream — tracks the starter's master, stays clean
git checkout -b upstream "starter/$STARTER_BRANCH"
echo "  Created: upstream (tracks starter/$STARTER_BRANCH)"

# develop — branched from upstream at project start
git checkout -b develop
echo "  Created: develop (branched from upstream)"

# main — branched from develop at project start
git checkout -b main
echo "  Created: main (branched from develop)"

# --- Step 3: Record starter origin ---
echo ""
echo "[3/6] Recording starter origin..."

INIT_COMMIT=$(git rev-parse HEAD)
STARTER_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "untagged")

printf 'starter-repo: %s\nfork-repo: %s\nstarter-tag: %s\ninit-commit: %s\ninit-date: %s\n' \
    "$STARTER_REPO" "$FORK_REPO" "$STARTER_TAG" "$INIT_COMMIT" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    > .starter-version

git add .starter-version
git commit -m "chore: record starter origin for upstream tracking

Based on starter $STARTER_TAG ($INIT_COMMIT)"

# --- Step 4: Push branches to the fork ---
echo ""
echo "[4/6] Pushing branches..."
git push -u origin main
git push -u origin develop
git push -u origin upstream

# --- Step 5: Set working branch ---
echo ""
echo "[5/6] Setting develop as the working branch..."
git checkout develop

# Clean up the starter's default branch locally (we use upstream instead)
echo ""
echo "  NOTE: Remember to change the fork's default branch to 'main' in Bitbucket"
echo "        (Repository settings > Repository details > Main branch > main)"
echo "        before deleting the remote master branch."
git branch -d master 2>/dev/null || true

# --- Step 6: Configure fetch rules ---
echo ""
echo "[6/6] Configuring fetch rules..."

# Only fetch master from the starter remote (we don't need its feature branches)
git config remote.starter.fetch "+refs/heads/$STARTER_BRANCH:refs/remotes/starter/$STARTER_BRANCH"

echo ""
echo "============================================"
echo "  Setup complete!"
echo "============================================"
echo ""
echo "  Branch structure:"
echo "    main     — production deployments"
echo "    develop  — staging/development (you are here)"
echo "    upstream — starter tracking (do not commit to this)"
echo ""
echo "  Remotes:"
echo "    origin  — $FORK_REPO (your fork)"
echo "    starter — $STARTER_REPO (upstream source)"
echo ""
echo "  Next steps:"
echo "    1. Change the fork's default branch to 'main' in Bitbucket"
echo "    2. Set up Bitbucket branch permissions (see git_workflow_customer_projects.md)"
echo "    3. Configure Envoyer for deployments"
echo "    4. Create your .env and run: sh setup.sh"
echo ""
echo "  To pull starter updates later:"
echo "    git fetch starter && git checkout upstream && git merge starter/master"
echo "    git push origin upstream && git checkout develop && git merge upstream"
echo ""
