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

# ────────────────
# Config
# ────────────────
GIT_REMOTE_NAME="origin"
REPO_NAME=$(basename "$(pwd)")
DEFAULT_NAME="Mark Randall Havens"
DEFAULT_EMAIL="mark.r.havens@gmail.com"
GITLAB_WEB="https://gitlab.com"
GITLAB_API="$GITLAB_WEB/api/v4"
GITLAB_SSH="git@gitlab.com"

# ────────────────
# Logging
# ────────────────
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; }

# ────────────────
# Git Identity
# ────────────────
git config --global user.name "$DEFAULT_NAME"
git config --global user.email "$DEFAULT_EMAIL"
info "Git identity set to: $DEFAULT_NAME <$DEFAULT_EMAIL>"

# ────────────────
# Git Repo Init
# ────────────────
if [ ! -d .git ]; then
  info "Initializing Git repo..."
  git init
  git add . || warn "Nothing to add"
  git commit -m "Initial commit" || warn "Nothing to commit"
else
  info "Git repo already initialized."
fi

# ────────────────
# Ensure First Commit
# ────────────────
if ! git rev-parse HEAD &>/dev/null; then
  git add . && git commit -m "Initial commit" || warn "Nothing to commit"
fi

# ────────────────
# SSH Key Setup
# ────────────────
if [ ! -f ~/.ssh/id_rsa ]; then
  info "Generating SSH key..."
  ssh-keygen -t rsa -b 4096 -C "$DEFAULT_EMAIL" -f ~/.ssh/id_rsa -N "" || error "Failed to generate SSH key"
fi

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa || error "Failed to add SSH key"

# ────────────────
# GitLab Token Prompt
# ────────────────
echo
echo "🔐 Paste your GitLab Personal Access Token (scopes: api, read_user, write_repository, write_ssh_key)"
echo "→ Generate at: $GITLAB_WEB/-/profile/personal_access_tokens"
read -rp "🔑 Token: " TOKEN

# ────────────────
# Get GitLab Username (via API)
# ────────────────
USERNAME=$(curl -s --header "PRIVATE-TOKEN: $TOKEN" "$GITLAB_API/user" | grep -oP '(?<="username":")[^"]*') || {
  error "Failed to retrieve username — invalid token?"
}
info "GitLab username detected: $USERNAME"

# ────────────────
# Register SSH Key (if missing)
# ────────────────
if ! ssh -T "$GITLAB_SSH" 2>&1 | grep -q "Welcome"; then
  PUBKEY=$(<~/.ssh/id_rsa.pub)
  TITLE="AutoKey-$(hostname)-$(date +%s)"
  info "Uploading SSH key to GitLab..."
  curl -s --fail -X POST "$GITLAB_API/user/keys" \
    -H "PRIVATE-TOKEN: $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"title\": \"$TITLE\", \"key\": \"$PUBKEY\"}" || warn "SSH key may already exist or failed to upload"
  sleep 2
fi

# ────────────────
# Create Repository (via API)
# ────────────────
REPO_API_URL="$GITLAB_API/projects"
REPO_PAYLOAD="{\"name\": \"$REPO_NAME\", \"visibility\": \"public\"}"

info "Creating GitLab repository '$REPO_NAME'..."
if curl -s --fail -X POST "$REPO_API_URL" \
    -H "PRIVATE-TOKEN: $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$REPO_PAYLOAD" | grep -q '"ssh_url_to_repo":'; then
  info "Repository created successfully."
else
  warn "Repository may already exist or creation failed — continuing..."
fi

# ────────────────
# Add SSH Remote
# ────────────────
REMOTE_URL="$GITLAB_SSH:$USERNAME/$REPO_NAME.git"
if ! git remote get-url "$GIT_REMOTE_NAME" &>/dev/null; then
  git remote add "$GIT_REMOTE_NAME" "$REMOTE_URL"
  info "SSH remote set to: $REMOTE_URL"
else
  info "Remote already exists: $(git remote get-url "$GIT_REMOTE_NAME")"
fi

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

BRANCH=$(git rev-parse --abbrev-ref HEAD)
if ! git config --get branch."$BRANCH".remote &>/dev/null; then
  info "Pushing with upstream..."
  git push -u "$GIT_REMOTE_NAME" "$BRANCH" || error "Push failed"
else
  info "Pushing to $GIT_REMOTE_NAME/$BRANCH..."
  git push "$GIT_REMOTE_NAME" "$BRANCH" || error "Push failed"
fi
