#!/bin/bash
#
# dev_commit.sh - Development snapshot and commit helper
#
# Usage: ./dev_commit.sh "Commit message here"
#
# This script:
# 1. Creates a database snapshot (overwrites previous)
# 2. Stages all changes (git add -A)
# 3. Commits with the provided message
#

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
DB_USER="wordpress"
DB_PASS="wordpress"
DB_NAME="wordpress"
SNAPSHOT_FILE="/var/www/html/db-snapshots/db-snapshot.sql"
WEBROOT="/var/www/html"

# Check if message was provided
if [ -z "$1" ]; then
    echo -e "${YELLOW}Usage:${NC} ./dev_commit.sh \"Commit message here\""
    echo ""
    echo "This script performs a development checkpoint:"
    echo "  1. Dumps the database to db-snapshots/db-snapshot.sql"
    echo "  2. Stages all changes (git add -A)"
    echo "  3. Commits with your message"
    echo ""
    echo -e "${RED}Error:${NC} No commit message provided."
    exit 1
fi

COMMIT_MSG="$1"

echo -e "${YELLOW}[1/3]${NC} Creating database snapshot..."
mysqldump -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" > "$SNAPSHOT_FILE" 2>/dev/null

if [ $? -ne 0 ]; then
    echo -e "${RED}Error:${NC} Database dump failed."
    exit 1
fi

echo -e "${GREEN}Done${NC} - Database snapshot saved to db-snapshots/db-snapshot.sql"

echo -e "${YELLOW}[2/3]${NC} Staging all changes..."
cd "$WEBROOT" || exit 1
git add -A

if [ $? -ne 0 ]; then
    echo -e "${RED}Error:${NC} Git add failed."
    exit 1
fi

echo -e "${GREEN}Done${NC} - All changes staged"

echo -e "${YELLOW}[3/3]${NC} Committing..."
git commit -m "$COMMIT_MSG"

if [ $? -ne 0 ]; then
    echo -e "${YELLOW}Note:${NC} Nothing to commit or commit failed."
    exit 0
fi

echo -e "${GREEN}Done${NC} - Committed: $COMMIT_MSG"
echo ""
echo -e "${GREEN}Complete.${NC} Snapshot and commit finished."
