#!/bin/bash

# Direct Docker Deployment Script
# This script deploys rmtPocketWatcher directly to a Docker host via SSH

set -e

# Configuration
DOCKER_HOST="${DOCKER_HOST:-localhost}"
DOCKER_USER="${DOCKER_USER:-root}"
DEPLOY_PATH="${DEPLOY_PATH:-/opt/rmtpocketwatcher}"
GIT_REPO="${GIT_REPO}"
GIT_BRANCH="${GIT_BRANCH:-main}"

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

echo -e "${GREEN}Deploying rmtPocketWatcher to Docker host...${NC}"

# Check if we're deploying locally or remotely
if [ "$DOCKER_HOST" = "localhost" ]; then
    echo -e "${YELLOW}Deploying locally...${NC}"
    
    # Pull latest code
    if [ -d "$DEPLOY_PATH" ]; then
        cd "$DEPLOY_PATH"
        git pull origin "$GIT_BRANCH"
    else
        git clone -b "$GIT_BRANCH" "$GIT_REPO" "$DEPLOY_PATH"
        cd "$DEPLOY_PATH"
    fi
    
    # Build and deploy
    docker-compose down
    docker-compose build backend
    docker-compose up -d
    
    echo -e "${GREEN}Local deployment complete!${NC}"
else
    echo -e "${YELLOW}Deploying to remote host: ${DOCKER_HOST}${NC}"
    
    # Deploy via SSH
    ssh ${DOCKER_USER}@${DOCKER_HOST} << EOF
        set -e
        
        # Pull or clone repository
        if [ -d "${DEPLOY_PATH}" ]; then
            cd "${DEPLOY_PATH}"
            git pull origin ${GIT_BRANCH}
        else
            git clone -b ${GIT_BRANCH} ${GIT_REPO} ${DEPLOY_PATH}
            cd "${DEPLOY_PATH}"
        fi
        
        # Build and deploy
        docker-compose down
        docker-compose build backend
        docker-compose up -d
        
        echo "Deployment complete!"
EOF
    
    echo -e "${GREEN}Remote deployment complete!${NC}"
fi

# Show status
echo -e "${YELLOW}Checking service status...${NC}"
if [ "$DOCKER_HOST" = "localhost" ]; then
    docker-compose ps
else
    ssh ${DOCKER_USER}@${DOCKER_HOST} "cd ${DEPLOY_PATH} && docker-compose ps"
fi
