#!/bin/bash
# Skrypt deploymentu KSEF na serwer produkcji
# Użycie: ./deploy.sh <user@host> <remote_dir>

set -e  # Exit on error

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

# Parametry
REMOTE_HOST="${1:-ms@10.1.1.3}"
REMOTE_DIR="${2:-/var/www/ksef}"

echo -e "${YELLOW}🚀 KSEF Deployment Script${NC}"
echo "Remote host: $REMOTE_HOST"
echo "Remote dir:  $REMOTE_DIR"
echo ""

# Krok 1: Build aplikacji
echo -e "${YELLOW}1️⃣  Building application...${NC}"
if [ ! -d "src/app-public" ]; then
    echo -e "${RED}❌ Error: src/app-public not found. Run from project root!${NC}"
    exit 1
fi

npm run build:app

if [ ! -d "dist-app" ]; then
    echo -e "${RED}❌ Error: dist-app not created!${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Build complete${NC}"
echo ""

# Krok 2: Sprawdzenie SSH dostępu
echo -e "${YELLOW}2️⃣  Checking SSH access...${NC}"
if ! ssh -q "$REMOTE_HOST" "test -d /var/www"; then
    echo -e "${RED}❌ SSH connection failed or /var/www not found${NC}"
    exit 1
fi
echo -e "${GREEN}✓ SSH OK${NC}"
echo ""

# Krok 3: Stworzenie folderu
echo -e "${YELLOW}3️⃣  Creating remote directory...${NC}"
ssh "$REMOTE_HOST" "mkdir -p $REMOTE_DIR"
echo -e "${GREEN}✓ Directory ready${NC}"
echo ""

# Krok 4: Upload artefaktów
echo -e "${YELLOW}4️⃣  Uploading files...${NC}"
scp -r dist-app/* "$REMOTE_HOST:$REMOTE_DIR/"
echo -e "${GREEN}✓ Files uploaded${NC}"
echo ""

# Krok 5: Ustaw uprawnienia
echo -e "${YELLOW}5️⃣  Setting permissions...${NC}"
ssh "$REMOTE_HOST" "sudo chown -R www-data:www-data $REMOTE_DIR && sudo chmod -R 755 $REMOTE_DIR"
echo -e "${GREEN}✓ Permissions set${NC}"
echo ""

# Krok 6: Reload nginx
echo -e "${YELLOW}6️⃣  Reloading nginx...${NC}"
ssh "$REMOTE_HOST" "sudo nginx -t && sudo systemctl reload nginx"
echo -e "${GREEN}✓ Nginx reloaded${NC}"
echo ""

echo -e "${GREEN}✅ Deployment complete!${NC}"
echo -e "Application running at: ${YELLOW}http://www.sic.pl/ksef/${NC}"
echo ""
echo "Logs:"
echo "  Errors: ssh $REMOTE_HOST 'sudo tail -f /var/log/nginx/error.log'"
echo "  Access: ssh $REMOTE_HOST 'sudo tail -f /var/log/nginx/access.log | grep ksef'"
