#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

# ╭────────── Configuration ──────────╮
REMOTE_NAME="bitbucket"
WORKSPACE="thefoldwithin"
REPO_NAME=$(basename "$(pwd)")
USERNAME="mrhavens"
EMAIL="mark.r.havens@gmail.com"
BB_API="https://api.bitbucket.org/2.0/repositories/$WORKSPACE/$REPO_NAME"
CRED_FILE="$HOME/.bitbucket_app_password"

# ╭────────── Logging Helpers ──────────╮
info()  { echo -e "\e[1;34m[INFO]\e[0m $*"; }
warn()  { echo -e "\e[1;33m[WARN]\e[0m $*"; }
error() { echo -e "\e[1;31m[ERROR]\e[0m $*" >&2; exit 1; }

# ╭────────── Prerequisites ──────────╮
info "Checking prerequisites..."
sudo apt update -qq
sudo apt install -y git curl openssh-client jq || error "Missing packages"

# ╭────────── Git Identity ──────────╮
git config --global user.name "$USERNAME"
git config --global user.email "$EMAIL"
info "Git identity: $USERNAME <$EMAIL>"

# ╭────────── SSH Key Setup ──────────╮
if [ ! -f ~/.ssh/id_rsa ]; then
  info "Generating SSH key..."
  ssh-keygen -t rsa -b 4096 -C "$EMAIL" -f ~/.ssh/id_rsa -N ""
fi

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

# ╭────────── Git Initialization ──────────╮
if [ ! -d .git ]; then
  info "Initializing git..."
  git init
  git add . || warn "Nothing to add"
  git commit -m "Initial commit" || warn "Nothing to commit"
else
  info "Git repository already exists."
fi

# ╭────────── Bitbucket Credential ──────────╮
if [ ! -f "$CRED_FILE" ]; then
  echo
  echo "🔐 Please paste your Bitbucket App Password (scopes: Repositories + SSH)"
  echo "→ Create one at: https://bitbucket.org/account/settings/app-passwords/"
  read -rsp "🔑 App Password: " BB_PASSWORD
  echo "$BB_PASSWORD" > "$CRED_FILE"
  chmod 600 "$CRED_FILE"
  echo
  info "Stored app password in $CRED_FILE"
fi

BB_PASSWORD=$(<"$CRED_FILE")

# ╭────────── Create Repo via API ──────────╮
if ! curl -s -u "$USERNAME:$BB_PASSWORD" "$BB_API" | grep -q '"slug":'; then
  info "Creating Bitbucket repository '$REPO_NAME'..."
  curl -s -X POST -u "$USERNAME:$BB_PASSWORD" "$BB_API" \
    -H "Content-Type: application/json" \
    -d "{\"scm\": \"git\", \"is_private\": false}" | jq .
else
  warn "Repo may already exist or is already accessible"
fi

# ╭────────── Set Git Remote ──────────╮
REMOTE_URL="git@bitbucket.org:$WORKSPACE/$REPO_NAME.git"
if git remote get-url "$REMOTE_NAME" &>/dev/null; then
  info "Remote '$REMOTE_NAME' already set to: $(git remote get-url "$REMOTE_NAME")"
else
  git remote add "$REMOTE_NAME" "$REMOTE_URL"
  info "Remote added: $REMOTE_URL"
fi

# ╭────────── Commit + Push Logic ──────────╮
if ! git diff --quiet || ! git diff --cached --quiet; then
  git add .
  git commit -m "Update: $(date '+%Y-%m-%d %H:%M:%S')" || warn "Nothing to commit"
else
  info "No uncommitted changes."
fi

BRANCH=$(git rev-parse --abbrev-ref HEAD)
info "Pushing to '$REMOTE_NAME/$BRANCH'..."
git push -u "$REMOTE_NAME" "$BRANCH" || error "Push failed"

info "✅ Bitbucket push completed successfully."
