File size: 7,100 Bytes
3718c84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
#!/bin/bash
# Script khởi động PostgreSQL và ngrok tunnel với port và URL cố định
# Sử dụng: ./khoidongDB.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
OPS_DIR="$PROJECT_ROOT/ops"
ENV_TUNNEL="$OPS_DIR/.env.tunnel"

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

log() {
    echo -e "${GREEN}[DB-START]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[DB-START]${NC} $1"
}

error() {
    echo -e "${RED}[DB-START]${NC} $1"
}

# Load config
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

# Default values
POSTGRES_PORT=${POSTGRES_PORT:-5543}
NGROK_REGION=${NGROK_REGION:-ap}
NGROK_API_URL="http://127.0.0.1:4040"

# Create ops directory if not exists
mkdir -p "$OPS_DIR"

# Function to check if PostgreSQL is running
check_postgres() {
    log "Kiểm tra PostgreSQL trên port $POSTGRES_PORT..."
    
    if command -v psql &> /dev/null; then
        if PGPASSWORD="${POSTGRES_PASSWORD:-huepass123}" psql -h localhost -p "$POSTGRES_PORT" -U "${POSTGRES_USER:-hue_remote}" -d "${POSTGRES_DB:-hue_portal}" -c "SELECT 1;" &> /dev/null; then
            log "✅ PostgreSQL đang chạy trên port $POSTGRES_PORT"
            return 0
        fi
    fi
    
    # Try Python connection
    if [ -f "$PROJECT_ROOT/backend/venv/bin/python" ]; then
        if "$PROJECT_ROOT/backend/venv/bin/python" -c "
import psycopg2
try:
    conn = psycopg2.connect(
        host='localhost',
        port=$POSTGRES_PORT,
        database='${POSTGRES_DB:-hue_portal}',
        user='${POSTGRES_USER:-hue_remote}',
        password='${POSTGRES_PASSWORD:-huepass123}',
        connect_timeout=2
    )
    conn.close()
    exit(0)
except:
    exit(1)
" 2>/dev/null; then
            log "✅ PostgreSQL đang chạy trên port $POSTGRES_PORT"
            return 0
        fi
    fi
    
    warn "⚠️  PostgreSQL không chạy trên port $POSTGRES_PORT"
    return 1
}

# Function to get ngrok tunnel URL
get_ngrok_url() {
    local host port
    if command -v curl &> /dev/null && command -v python3 &> /dev/null; then
        response=$(curl -s "$NGROK_API_URL/api/tunnels" 2>/dev/null || echo "")
        if [ -n "$response" ]; then
            # Use Python to parse JSON properly
            ngrok_url=$(echo "$response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    for tunnel in data.get('tunnels', []):
        if tunnel.get('proto') == 'tcp':
            public_url = tunnel.get('public_url', '')
            if public_url.startswith('tcp://'):
                url = public_url.replace('tcp://', '')
                print(url)
                sys.exit(0)
except:
    pass
" 2>/dev/null)
            if [ -n "$ngrok_url" ]; then
                echo "$ngrok_url"
                return 0
            fi
        fi
    fi
    return 1
}

# Function to start ngrok
start_ngrok() {
    log "Khởi động ngrok tunnel..." >&2
    
    # Check if ngrok is already running
    if curl -s "$NGROK_API_URL/api/tunnels" &> /dev/null; then
        ngrok_url=$(get_ngrok_url)
        if [ -n "$ngrok_url" ]; then
            log "✅ Ngrok đã chạy sẵn: tcp://$ngrok_url" >&2
            echo "$ngrok_url"
            return 0
        fi
    fi
    
    # Kill existing ngrok processes
    pkill -f "ngrok tcp" 2>/dev/null || true
    sleep 1
    
    # Start ngrok
    log "Đang start ngrok (ngrok tcp $POSTGRES_PORT --region $NGROK_REGION)..." >&2
    nohup ngrok tcp "$POSTGRES_PORT" --region "$NGROK_REGION" --log=stdout > "$OPS_DIR/ngrok.log" 2>&1 &
    NGROK_PID=$!
    
    # Wait for ngrok to start
    for i in {1..10}; do
        sleep 1
        if curl -s "$NGROK_API_URL/api/tunnels" &> /dev/null; then
            ngrok_url=$(get_ngrok_url)
            if [ -n "$ngrok_url" ]; then
                log "✅ Ngrok đã sẵn sàng: tcp://$ngrok_url" >&2
                echo "$ngrok_url"
                return 0
            fi
        fi
    done
    
    error "❌ Không thể khởi động ngrok" >&2
    return 1
}

# Function to update DATABASE_URL on Hugging Face Space
update_hf_space() {
    local host=$1
    local port=$2
    
    if [ -z "$host" ] || [ -z "$port" ]; then
        warn "⚠️  Không có ngrok URL, bỏ qua cập nhật HF Space"
        return 1
    fi
    
    log "Cập nhật DATABASE_URL lên Hugging Face Space..."
    
    if [ -f "$PROJECT_ROOT/backend/venv/bin/python" ]; then
        "$PROJECT_ROOT/backend/venv/bin/python" "$SCRIPT_DIR/start_ngrok_and_set_db.py" 2>&1 | grep -E "(✅|❌|📌)" || true
    else
        warn "⚠️  Không tìm thấy Python venv, bỏ qua cập nhật HF Space"
    fi
}

# Function to save tunnel info
save_tunnel_info() {
    local host=$1
    local port=$2
    
    if [ -z "$host" ] || [ -z "$port" ]; then
        return 1
    fi
    
    log "Lưu thông tin tunnel..."
    
    cat > "$ENV_TUNNEL" << EOF
# Ngrok tunnel info - Generated by khoidongDB.sh
# Last updated: $(date -u +"%Y-%m-%dT%H:%M:%S")

PG_TUNNEL_HOST=$host
PG_TUNNEL_PORT=$port
PG_TUNNEL_LOCAL_PORT=$POSTGRES_PORT
PG_TUNNEL_USER=${POSTGRES_USER:-hue_remote}
PG_TUNNEL_PASSWORD=${POSTGRES_PASSWORD:-huepass123}
PG_TUNNEL_DB=${POSTGRES_DB:-hue_portal}
DATABASE_URL=postgres://${POSTGRES_USER:-hue_remote}:${POSTGRES_PASSWORD:-huepass123}@$host:$port/${POSTGRES_DB:-hue_portal}
HF_SPACE_ID=${HF_SPACE_ID:-davidtran999/hue-portal-backend}
POSTGRES_HOST=${POSTGRES_HOST:-localhost}
POSTGRES_PORT=$POSTGRES_PORT
POSTGRES_USER=${POSTGRES_USER:-hue_remote}
POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-huepass123}
POSTGRES_DB=${POSTGRES_DB:-hue_portal}
PG_TUNNEL_LAST_UPDATED=$(date -u +"%Y-%m-%dT%H:%M:%S")
EOF
    
    log "✅ Đã lưu tunnel info vào $ENV_TUNNEL"
}

# Main execution
main() {
    log "============================================================"
    log "Khởi động PostgreSQL và ngrok tunnel"
    log "============================================================"
    
    # Check PostgreSQL
    if ! check_postgres; then
        error "❌ PostgreSQL không chạy trên port $POSTGRES_PORT"
        error "   Vui lòng khởi động PostgreSQL trước"
        exit 1
    fi
    
    # Start ngrok
    ngrok_url=$(start_ngrok)
    if [ $? -ne 0 ] || [ -z "$ngrok_url" ]; then
        error "❌ Không thể khởi động ngrok"
        exit 1
    fi
    
    ngrok_host=$(echo "$ngrok_url" | cut -d':' -f1)
    ngrok_port=$(echo "$ngrok_url" | cut -d':' -f2)
    
    # Save tunnel info
    save_tunnel_info "$ngrok_host" "$ngrok_port"
    
    # Update Hugging Face Space
    update_hf_space "$ngrok_host" "$ngrok_port"
    
    log "============================================================"
    log "✅ Hoàn tất!"
    log "   PostgreSQL: localhost:$POSTGRES_PORT"
    log "   Ngrok tunnel: tcp://$ngrok_host:$ngrok_port"
    log "   DATABASE_URL: postgres://${POSTGRES_USER:-hue_remote}:***@$ngrok_host:$ngrok_port/${POSTGRES_DB:-hue_portal}"
    log "============================================================"
}

# Run main
main "$@"