#!/bin/bash
# Load production credentials from GitBucket if they are missing from the environment
if [ -z "$REMOTE_PASSWORD" ] || [ -z "$REMOTE_HOST" ] || [ -z "$REMOTE_USER" ]; then
    # Load GitBucket token if present
    if [ -f "$LOCAL_APP_DIR/.env.gitbucket" ]; then
        source "$LOCAL_APP_DIR/.env.gitbucket"
    elif [ -f "./.env.gitbucket" ]; then
        source "./.env.gitbucket"
    fi

    if [ -n "$GITBUCKET_TOKEN" ] && [ -n "$DEPLOYMENT_SNIPPET_ID" ]; then
        # echo "Secrets missing. Fetching from GitBucket..." >&2
        TMP_SECRETS=$(mktemp -d)
        if git clone "https://yangyangxie:${GITBUCKET_TOKEN}@gitbucket.jerxie.com/git/gist/yangyangxie/${DEPLOYMENT_SNIPPET_ID}.git" "$TMP_SECRETS" &> /dev/null; then
            if [ -f "$TMP_SECRETS/.env.production" ]; then
                # Use a temp file to extract values without contaminating the whole env immediately
                REMOTE_HOST=$(grep "REMOTE_HOST=" "$TMP_SECRETS/.env.production" | cut -d'=' -f2 | tr -d '\r')
                REMOTE_USER=$(grep "REMOTE_USER=" "$TMP_SECRETS/.env.production" | cut -d'=' -f2 | tr -d '\r')
                REMOTE_PASSWORD=$(grep "REMOTE_PASSWORD=" "$TMP_SECRETS/.env.production" | cut -d'=' -f2 | tr -d '\r')
                # Fallback to REMOTE_PASS if REMOTE_PASSWORD missing
                if [ -z "$REMOTE_PASSWORD" ]; then
                    REMOTE_PASSWORD=$(grep "REMOTE_PASS=" "$TMP_SECRETS/.env.production" | cut -d'=' -f2 | tr -d '\r')
                fi
            fi
        fi
        rm -rf "$TMP_SECRETS"
    fi
fi

# Fallback defaults
export REMOTE_HOST="${REMOTE_HOST:-192.168.68.113}"
export REMOTE_USER="${REMOTE_USER:-axieyangb}"
export REMOTE_PASSWORD="${REMOTE_PASSWORD}"

if [ -z "$REMOTE_PASSWORD" ]; then
    echo "Error: REMOTE_PASSWORD not found. Please check GitBucket secrets or set manually." >&2
    exit 1
fi
