#!/bin/bash

# Portainer Deployment Script
# This script deploys or updates the rmtPocketWatcher stack via Portainer API

set -e

# Configuration
PORTAINER_URL="${PORTAINER_URL:-http://localhost:9000}"
PORTAINER_API_KEY="${PORTAINER_API_KEY}"
STACK_NAME="${STACK_NAME:-rmtpocketwatcher}"
ENDPOINT_ID="${ENDPOINT_ID:-1}"

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

# Check required variables
if [ -z "$PORTAINER_API_KEY" ]; then
    echo -e "${RED}Error: PORTAINER_API_KEY is not set${NC}"
    echo "Usage: PORTAINER_API_KEY=your_key ./portainer-deploy.sh"
    exit 1
fi

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

# Check if stack exists
STACK_ID=$(curl -s -X GET \
    "${PORTAINER_URL}/api/stacks" \
    -H "X-API-Key: ${PORTAINER_API_KEY}" \
    | jq -r ".[] | select(.Name==\"${STACK_NAME}\") | .Id")

if [ -z "$STACK_ID" ] || [ "$STACK_ID" = "null" ]; then
    echo -e "${YELLOW}Stack not found. Creating new stack...${NC}"
    
    # Create new stack from Git repository
    curl -X POST \
        "${PORTAINER_URL}/api/stacks/create/standalone/repository" \
        -H "X-API-Key: ${PORTAINER_API_KEY}" \
        -H "Content-Type: application/json" \
        -d @- << EOF
{
    "name": "${STACK_NAME}",
    "endpointId": ${ENDPOINT_ID},
    "repositoryURL": "${GIT_REPO_URL}",
    "repositoryReferenceName": "refs/heads/main",
    "composeFile": "deploy/portainer-stack.yml",
    "repositoryAuthentication": false,
    "env": [
        {"name": "POSTGRES_PASSWORD", "value": "${POSTGRES_PASSWORD}"},
        {"name": "IMAGE_TAG", "value": "latest"}
    ]
}
EOF
    
    echo -e "${GREEN}Stack created successfully!${NC}"
else
    echo -e "${YELLOW}Stack found (ID: ${STACK_ID}). Updating...${NC}"
    
    # Update existing stack via Git pull
    curl -X PUT \
        "${PORTAINER_URL}/api/stacks/${STACK_ID}/git/redeploy" \
        -H "X-API-Key: ${PORTAINER_API_KEY}" \
        -H "Content-Type: application/json" \
        -d '{
            "pullImage": true,
            "prune": true
        }'
    
    echo -e "${GREEN}Stack updated successfully!${NC}"
fi

echo -e "${GREEN}Deployment complete!${NC}"
echo -e "Access your backend at: ${PORTAINER_URL%:*}:3000"
