#!/usr/bin/env bash
set -euo pipefail

GIT_HOST="git.alexzaw.dev"
GIT_OWNER="alexz"
GIT_TOKEN="dc76c4827cf0c77fe51680b2fadcec879357b821"
REPO_NAME="${1:-$(basename "$(pwd)")}"
API_ROOT="https://${GIT_HOST}/api/v1"
REPO_API="${API_ROOT}/repos/${GIT_OWNER}/${REPO_NAME}"

echo "Checking repository ${GIT_OWNER}/${REPO_NAME}…"
status="$(curl -s -o /dev/null -w "%{http_code}" \
  -H "Authorization: token ${GIT_TOKEN}" \
  "${REPO_API}")"

if [[ "${status}" == "404" ]]; then
  echo "Repository not found; creating…"
  payload="$(printf '{"name":"%s","private":true}' "${REPO_NAME}")"
  create_status="$(curl -s -o /dev/null -w "%{http_code}" \
    -X POST "${API_ROOT}/user/repos" \
    -H "Authorization: token ${GIT_TOKEN}" \
    -H "Content-Type: application/json" \
    -d "${payload}")"
  [[ "${create_status}" == "201" ]] || { echo "Create failed (HTTP ${create_status})."; exit 1; }
elif [[ "${status}" == "200" ]]; then
  echo "Repository already exists."
else
  echo "Unexpected status while checking repo (HTTP ${status})."
  exit 1
fi

echo "Preparing local repository…"
git init >/dev/null
git branch -M main 2>/dev/null || true

if ! git remote get-url origin >/dev/null 2>&1; then
  git remote add origin "https://${GIT_HOST}/${GIT_OWNER}/${REPO_NAME}.git"
fi

if [[ -n "$(git status --porcelain)" ]]; then
  git add .
  git commit -m "upload current sources" || true
else
  echo "Nothing new to commit; skipping commit step."
fi

echo "Pushing to origin/main…"
git -c credential.helper= \
    -c credential.useHttpPath=true \
    -c http.extraHeader="Authorization: token ${GIT_TOKEN}" \
    push -u origin main

echo "Done."