#!/bin/bash

# Script to deploy and execute role update for ben@measurequick.com on production

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_SCRIPT="$SCRIPT_DIR/update-ben-roles.sh"

# Load environment variables
if [ -f "$SCRIPT_DIR/../.env" ]; then
    source "$SCRIPT_DIR/../.env"
else
    echo "ERROR: .env file not found!"
    exit 1
fi

echo "==========================================="
echo "Deploying role update to production"
echo "==========================================="

# Use the correct env var names from .env
PROD_SSH_USER="$UPSKILL_PROD_SSH_USER"
PROD_SSH_HOST="$UPSKILL_PROD_IP"
PROD_SSH_PATH="$UPSKILL_PROD_PATH"
PROD_SSH_PASSWORD="$UPSKILL_PROD_SSH_PASS"

# Check if required env vars are set
if [ -z "$PROD_SSH_USER" ] || [ -z "$PROD_SSH_HOST" ] || [ -z "$PROD_SSH_PATH" ]; then
    echo "ERROR: Production SSH credentials not configured in .env"
    echo "Please ensure UPSKILL_PROD_SSH_USER, UPSKILL_PROD_IP, and UPSKILL_PROD_PATH are set"
    exit 1
fi

echo "Uploading script to production server..."
if [ -n "$PROD_SSH_PASSWORD" ]; then
    # Use sshpass if password is available
    # First create tmp directory and upload there
    sshpass -p "$PROD_SSH_PASSWORD" ssh -o StrictHostKeyChecking=no "${PROD_SSH_USER}@${PROD_SSH_HOST}" "mkdir -p ~/tmp"
    sshpass -p "$PROD_SSH_PASSWORD" scp -o StrictHostKeyChecking=no "$SOURCE_SCRIPT" "${PROD_SSH_USER}@${PROD_SSH_HOST}:~/tmp/update-ben-roles.sh"
    
    echo -e "\nExecuting script on production..."
    sshpass -p "$PROD_SSH_PASSWORD" ssh -o StrictHostKeyChecking=no "${PROD_SSH_USER}@${PROD_SSH_HOST}" "cd ${PROD_SSH_PATH} && bash ~/tmp/update-ben-roles.sh && rm ~/tmp/update-ben-roles.sh"
else
    # Use key-based auth
    ssh -o StrictHostKeyChecking=no "${PROD_SSH_USER}@${PROD_SSH_HOST}" "mkdir -p ~/tmp"
    scp -o StrictHostKeyChecking=no "$SOURCE_SCRIPT" "${PROD_SSH_USER}@${PROD_SSH_HOST}:~/tmp/update-ben-roles.sh"
    
    echo -e "\nExecuting script on production..."
    ssh -o StrictHostKeyChecking=no "${PROD_SSH_USER}@${PROD_SSH_HOST}" "cd ${PROD_SSH_PATH} && bash ~/tmp/update-ben-roles.sh && rm ~/tmp/update-ben-roles.sh"
fi

echo -e "\nRole update completed successfully!"
echo "==========================================="