#!/bin/bash

# Setup GitHub Remote Backup Script
# This script helps you configure GitHub as a remote backup location

set -e

PROJECT_DIR="/var/www/html/erp_codearya"
cd "$PROJECT_DIR"

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

echo -e "${BLUE}=== GitHub Remote Backup Setup ===${NC}"
echo ""

# Check if Git is initialized
if [ ! -d ".git" ]; then
    echo -e "${RED}Error: Git repository not initialized!${NC}"
    echo -e "${YELLOW}Run build-with-backup.sh first to initialize Git.${NC}"
    exit 1
fi

# Check if remote already exists
if git remote | grep -q origin; then
    echo -e "${YELLOW}Remote 'origin' already exists:${NC}"
    git remote -v
    echo ""
    read -p "Do you want to update it? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Setup cancelled.${NC}"
        exit 0
    fi
    git remote remove origin
fi

echo -e "${GREEN}Step 1: GitHub Repository Setup${NC}"
echo ""
echo "You need to create a GitHub repository first:"
echo "1. Go to: https://github.com/new"
echo "2. Repository name: (e.g., erp-codearya-backup)"
echo "3. Make it PRIVATE (important for security!)"
echo "4. DO NOT initialize with README, .gitignore, or license"
echo "5. Click 'Create repository'"
echo ""
read -p "Have you created the GitHub repository? (y/N): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo -e "${YELLOW}Please create the repository first, then run this script again.${NC}"
    exit 0
fi

echo ""
echo -e "${GREEN}Step 2: Enter GitHub Repository URL${NC}"
echo ""
echo "Enter your GitHub repository URL:"
echo "Format: https://github.com/YOUR_USERNAME/REPO_NAME.git"
echo "   OR: git@github.com:YOUR_USERNAME/REPO_NAME.git"
echo ""
read -p "GitHub URL: " GITHUB_URL

if [ -z "$GITHUB_URL" ]; then
    echo -e "${RED}Error: GitHub URL is required!${NC}"
    exit 1
fi

# Add remote
echo ""
echo -e "${GREEN}Adding GitHub as remote backup...${NC}"
git remote add origin "$GITHUB_URL"

# Test connection
echo -e "${GREEN}Testing connection...${NC}"
if git ls-remote origin >/dev/null 2>&1; then
    echo -e "${GREEN}✅ Connection successful!${NC}"
else
    echo -e "${RED}❌ Connection failed!${NC}"
    echo -e "${YELLOW}Possible issues:${NC}"
    echo "  - Repository doesn't exist"
    echo "  - Authentication required (use SSH or Personal Access Token)"
    echo "  - Network issue"
    echo ""
    echo -e "${YELLOW}For HTTPS, you may need a Personal Access Token:${NC}"
    echo "  https://github.com/settings/tokens"
    echo ""
    read -p "Continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        git remote remove origin
        exit 1
    fi
fi

# Push everything
echo ""
echo -e "${GREEN}Pushing all backups to GitHub...${NC}"
echo "This may take a few minutes..."

# Push main branch
if git push -u origin master 2>&1 | tee /tmp/git-push.log; then
    echo -e "${GREEN}✅ Code pushed successfully!${NC}"
else
    echo -e "${YELLOW}⚠️  Push failed. Check the error above.${NC}"
    echo -e "${YELLOW}You may need to authenticate.${NC}"
    echo ""
    echo "For HTTPS: Use Personal Access Token as password"
    echo "For SSH: Make sure SSH key is added to GitHub"
    echo ""
    read -p "Try again? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        git push -u origin master
    fi
fi

# Push all tags (build backups)
echo ""
echo -e "${GREEN}Pushing build tags (backups)...${NC}"
if git push --tags 2>&1; then
    echo -e "${GREEN}✅ Build tags pushed successfully!${NC}"
else
    echo -e "${YELLOW}⚠️  Tags push failed, but code is backed up.${NC}"
fi

# Update build script to auto-push
echo ""
echo -e "${GREEN}Updating build script to auto-push to GitHub...${NC}"

# Check if auto-push is already added
if grep -q "git push origin" build-with-backup.sh; then
    echo -e "${YELLOW}Auto-push already configured in build script.${NC}"
else
    # Add auto-push at the end of build script
    cat >> build-with-backup.sh << 'AUTOPUSH_EOF'

# Push to remote backup (GitHub) if configured
if git remote | grep -q origin; then
    echo -e "${GREEN}Pushing to GitHub backup...${NC}"
    if git push origin master --tags 2>/dev/null; then
        echo -e "${GREEN}✅ Backed up to GitHub successfully!${NC}"
    else
        echo -e "${YELLOW}⚠️  GitHub push failed. Local backup still available.${NC}"
        echo -e "${YELLOW}   You can push manually later with: git push origin master --tags${NC}"
    fi
fi
AUTOPUSH_EOF
    echo -e "${GREEN}✅ Build script updated!${NC}"
fi

# Verify setup
echo ""
echo -e "${GREEN}=== Setup Complete! ===${NC}"
echo ""
echo -e "${GREEN}✅ GitHub remote configured${NC}"
echo -e "${GREEN}✅ All backups pushed to GitHub${NC}"
echo -e "${GREEN}✅ Auto-push enabled in build script${NC}"
echo ""
echo -e "${BLUE}Remote Backup Status:${NC}"
git remote -v
echo ""
echo -e "${BLUE}Next Steps:${NC}"
echo "1. Every time you run ./build-with-backup.sh, it will:"
echo "   - Create local backup"
echo "   - Automatically push to GitHub"
echo ""
echo "2. To manually push:"
echo "   git push origin master --tags"
echo ""
echo "3. To check backup status:"
echo "   ./check-backup-location.sh"
echo ""
echo -e "${GREEN}Your backups are now safely stored in the cloud! 🎉${NC}"
