tripweb/scripts/push-to-remote.sh

67 lines
1.7 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# push-to-remote.sh
# Usage: ./scripts/push-to-remote.sh [remote_url] [branch]
# If remote exists it will be used; otherwise added as 'origin'.
REMOTE_URL=${1:-https://git.algios.dev/francescoalbano/tripweb.git}
BRANCH=${2:-main}
print() { echo "[push-to-remote] $*"; }
# Ensure git repo
if [ ! -d .git ]; then
print "No .git found in current directory. Initialize and commit? (y/n)"
read -r yn
if [ "${yn,,}" != "y" ]; then
print "Aborting."; exit 1
fi
git init
git add .
git commit -m "Initial commit"
fi
# Ensure working tree clean
if [ -n "$(git status --porcelain)" ]; then
print "Working tree is not clean. Please commit or stash changes first.";
git status --porcelain
exit 1
fi
# Add remote if missing
if git remote get-url origin >/dev/null 2>&1; then
CURRENT_URL=$(git remote get-url origin)
if [ "$CURRENT_URL" != "$REMOTE_URL" ]; then
print "Remote 'origin' exists and points to $CURRENT_URL"
print "Do you want to set origin to $REMOTE_URL ? (y/n)"
read -r yn
if [ "${yn,,}" = "y" ]; then
git remote remove origin
git remote add origin "$REMOTE_URL"
else
print "Keeping existing origin. Aborting."; exit 1
fi
else
print "Remote 'origin' already set to $REMOTE_URL"
fi
else
git remote add origin "$REMOTE_URL"
print "Added origin -> $REMOTE_URL"
fi
# Ensure branch exists locally
if git rev-parse --verify "$BRANCH" >/dev/null 2>&1; then
git checkout "$BRANCH"
else
git checkout -b "$BRANCH"
fi
# Push
print "Pushing to origin/$BRANCH..."
# Use upstream set on first push
git push -u origin "$BRANCH"
print "Push complete. If this was the first push, create the repo on remote or ensure you have permission and the repo exists."
# End