#!/bin/bash

# Postiz Credentials Management Script
# Usage: ./update-credentials.sh youtube CLIENT_ID CLIENT_SECRET
# Or: ./update-credentials.sh list

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$SCRIPT_DIR/.env"
CONTAINER_NAME="postiz"

# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to update .env
update_env() {
    local key=$1
    local value=$2

    if grep -q "^${key}=" "$ENV_FILE"; then
        sed -i.bak "s|^${key}=.*|${key}=${value}|" "$ENV_FILE"
        echo -e "${GREEN}✓${NC} Updated ${key}"
    else
        echo "${key}=${value}" >> "$ENV_FILE"
        echo -e "${GREEN}✓${NC} Added ${key}"
    fi
}

# Function to show current credentials
show_credentials() {
    echo -e "${BLUE}Current Provider Credentials:${NC}"
    echo ""

    for provider in FACEBOOK TIKTOK LINKEDIN X YOUTUBE TELEGRAM; do
        client_id_var="${provider}_CLIENT_ID"
        client_secret_var="${provider}_CLIENT_SECRET"

        if [ "$provider" = "FACEBOOK" ]; then
            client_id_var="FACEBOOK_APP_ID"
            client_secret_var="FACEBOOK_APP_SECRET"
        fi

        id_val=$(grep "^${client_id_var}=" "$ENV_FILE" 2>/dev/null | cut -d= -f2- || echo "")
        secret_val=$(grep "^${client_secret_var}=" "$ENV_FILE" 2>/dev/null | cut -d= -f2- || echo "")

        if [ -z "$id_val" ] && [ -z "$secret_val" ]; then
            echo -e "${YELLOW}⚠${NC}  $provider: Not configured"
        else
            id_display="${id_val:0:10}..."
            secret_display=$(echo "$secret_val" | cut -c1-10)...
            echo -e "${GREEN}✓${NC}  $provider: ID=${id_display} Secret=${secret_display}"
        fi
    done
    echo ""
}

# Function to add/update provider
add_provider() {
    local provider=$1
    local client_id=$2
    local client_secret=$3

    case ${provider,,} in
        facebook)
            update_env "FACEBOOK_APP_ID" "$client_id"
            update_env "FACEBOOK_APP_SECRET" "$client_secret"
            ;;
        youtube)
            update_env "YOUTUBE_CLIENT_ID" "$client_id"
            update_env "YOUTUBE_CLIENT_SECRET" "$client_secret"
            ;;
        tiktok)
            update_env "TIKTOK_CLIENT_ID" "$client_id"
            update_env "TIKTOK_CLIENT_SECRET" "$client_secret"
            ;;
        linkedin)
            update_env "LINKEDIN_CLIENT_ID" "$client_id"
            update_env "LINKEDIN_CLIENT_SECRET" "$client_secret"
            ;;
        x|twitter)
            update_env "X_API_KEY" "$client_id"
            update_env "X_API_SECRET" "$client_secret"
            ;;
        telegram)
            update_env "TELEGRAM_BOT_NAME" "$client_id"
            update_env "TELEGRAM_BOT_TOKEN" "$client_secret"
            ;;
        *)
            echo -e "${RED}✗${NC} Unknown provider: $provider"
            echo "Supported providers: facebook, youtube, tiktok, linkedin, x, telegram"
            exit 1
            ;;
    esac
}

# Main logic
if [ $# -eq 0 ]; then
    show_credentials
    exit 0
fi

case ${1,,} in
    list)
        show_credentials
        ;;
    facebook|youtube|tiktok|linkedin|x|twitter|telegram)
        if [ $# -lt 3 ]; then
            echo -e "${RED}✗${NC} Usage: $0 $1 CLIENT_ID CLIENT_SECRET"
            echo ""
            echo "Example for YouTube:"
            echo "  $0 youtube 'YOUR_CLIENT_ID' 'YOUR_CLIENT_SECRET'"
            exit 1
        fi

        provider=$1
        client_id=$2
        client_secret=$3

        echo -e "${BLUE}Updating $provider credentials...${NC}"
        add_provider "$provider" "$client_id" "$client_secret"

        # Reload container
        echo -e "${YELLOW}Reloading Postiz container...${NC}"
        docker exec "$CONTAINER_NAME" pm2 restart backend workers frontend --wait-ready 2>/dev/null || true

        echo -e "${GREEN}✓${NC} Done! Credentials updated and services restarted"
        echo ""
        show_credentials
        ;;
    *)
        echo -e "${RED}✗${NC} Unknown command: $1"
        echo ""
        echo "Usage:"
        echo "  $0 list                         # Show current credentials"
        echo "  $0 youtube ID SECRET             # Add/update YouTube"
        echo "  $0 facebook ID SECRET            # Add/update Facebook"
        echo "  $0 tiktok ID SECRET              # Add/update TikTok"
        echo "  $0 linkedin ID SECRET            # Add/update LinkedIn"
        echo "  $0 x ID SECRET                   # Add/update X/Twitter"
        echo "  $0 telegram BOT_NAME BOT_TOKEN   # Add/update Telegram"
        exit 1
        ;;
esac
