#!/bin/bash
set -e

# ----------------------------------------
# 1. Configuration (UPDATE IF NEEDED)
# ----------------------------------------

GIT_USERNAME="asfautomation"
GIT_PASSWORD="asfautomation"

REPO_HOST="gitea.nabd-co.com"
REPO_PATH="ASF-Nabd/ASF-SH"
TARGET_DIR="TPF/Sensor_hub_repo"

# ----------------------------------------
# 2. URL Encoding Function
# ----------------------------------------
urlencode() {
    perl -pe 's/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge'
}

ENCODED_USERNAME=$(printf '%s' "${GIT_USERNAME}" | urlencode)
ENCODED_PASSWORD=$(printf '%s' "${GIT_PASSWORD}" | urlencode)


AUTH_URL="https://${ENCODED_USERNAME}:${ENCODED_PASSWORD}@${REPO_HOST}/${REPO_PATH}.git"

# ----------------------------------------
# 3. Command & Arguments
# ----------------------------------------
COMMAND="$1"
BRANCH_NAME="$2"

# ----------------------------------------
# 4. Functions
# ----------------------------------------

clone_repo() {
    if [ -d "${TARGET_DIR}" ]; then
        echo "ℹ️ Repository already exists. Skipping clone."
        return 0
    fi

    echo "📥 Cloning repository..."
    git clone "${AUTH_URL}" "${TARGET_DIR}"
    echo "✅ Clone completed."
}

checkout_branch() {
    if [ -z "${BRANCH_NAME}" ]; then
        echo "❌ Branch name is required for checkout."
        exit 1
    fi

    if [ ! -d "${TARGET_DIR}" ]; then
        echo "❌ Repository not found. Run clone first."
        exit 1
    fi

    cd "${TARGET_DIR}"

    echo "📦 Stashing local changes (including untracked)..."
    git stash push -u -m "automation-stash-before-checkout" || true

    echo "🔄 Fetching latest changes..."
    git fetch origin

    echo "🌿 Checking out main branch..."
    git checkout main

    echo "⬇️ Pulling latest main..."
    git pull "${AUTH_URL}" main

    echo "🌿 Checking out target branch: ${BRANCH_NAME}"
    if git show-ref --verify --quiet "refs/heads/${BRANCH_NAME}"; then
        git checkout "${BRANCH_NAME}"
    else
        git checkout -b "${BRANCH_NAME}" "origin/${BRANCH_NAME}"
    fi

    echo "⬆️ Rebasing '${BRANCH_NAME}' onto latest main..."
    git rebase main

    cd - >/dev/null
    echo "✅ Checkout and rebase completed successfully."
}

delete_repo() {
    if [ -d "${TARGET_DIR}" ]; then
        echo "🗑️ Deleting repository directory..."
        rm -rf "${TARGET_DIR}"
        echo "✅ Repository deleted."
    else
        echo "ℹ️ Repository directory does not exist."
    fi
}

# ----------------------------------------
# 5. Main Execution
# ----------------------------------------

case "${COMMAND}" in
    clone)
        clone_repo
        ;;
    checkout)
        checkout_branch
        ;;
    delete)
        delete_repo
        ;;
    *)
        echo "❌ Invalid command."
        echo "Usage:"
        echo "  $0 clone"
        echo "  $0 checkout <branch>"
        echo "  $0 delete"
        exit 1
        ;;
esac

echo "----------------------------------------"
echo "✔ Automation script finished successfully"
echo "----------------------------------------"
