start.sh 2.53 KB
Newer Older
1
#!/usr/bin/env bash
2
set -e
3
4

if ! command hypercorn &>/dev/null; then
5
    if [ ! -d ".venv" ]; then
6
7
        echo "Creating virtual environment"
        rm -f ".cur_branch"
8
        python -m venv --system-site-packages .venv
9
10
    fi  

11
12
13
14
    if [ -z "$VIRTUAL_ENV" ]; then
        echo "Switching to runtime environment..."
        source ".venv/bin/activate"
    fi
15

16
    _git_branch="$(git rev-parse --abbrev-ref HEAD)"
17
18
19
20
21
    if [ -f ".cur_branch" ]; then
        _cur_branch="$(cat .cur_branch 2>/dev/null)"
    else
        _cur_branch=""
    fi
22
23
24
25
26
27
28
29

    if [ "$_git_branch" != "$_cur_branch" ]; then
        echo "Reviewing dependency requirements, view .pip.log for details..."
        date >>".pip.log"
        pip --disable-pip-version-check install -r requirements.txt &>>".pip.log"
    fi

    echo "$_git_branch">".cur_branch"
30
31
fi

32
HTTP_HOST="${HTTP_HOST:-$HOSTNAME}"
33
34
35
36
37

HTTP_PORT="$(echo "$USER" | pcre2grep -o1 '(\d+)$' | xargs -I {} echo '9000+{}' | bc)"
HTTP_PORT="${HTTP_PORT:-9000}"

if [ "$HTTP_PORT" -ge 9000 ]; then
38
    ID="$(echo "$HTTP_PORT - 9000" | bc)"
39
    BIND="$HTTP_HOST:$HTTP_PORT"
40

41
    if curl -so /dev/null "$BIND"; then
42
        ./stop.sh
43
        echo "Re-starting service on $BIND..."
44
    else
45
        echo "Starting service $BIND..."
46
    fi
47
    
48
    hypercorn --debug --bind "$BIND" --log-level info --root-path="/$ID" "main:app" &>".main.log" &
49
50
51
52
53

    n=0 
    started=0
    while [ $started -eq 0 ] && [ $n -lt 10 ]; do
        n=$((n + 1))
54
        if curl -so /dev/null "$BIND"; then
55
56
            started=1
        else
57
            echo "Waiting 100ms for service to appear..."
58
59
60
61
62
63
            sleep 0.1 
        fi
    done

    if [ $started -eq 0 ]; then
        >&2 echo "Service failed to start in time, displaying log..."
64
        cat ".main.log" | less
65
        exit 1
66
67
68
69
70
71
72
73
    else
        # Watch for file changes, and restart if true...

        cp ".new_files" ".current_files" &>/dev/null

        (
        while ./pid.sh >/dev/null; do
            sleep 0.5
74
            find . -type f -regex '.*\(\.html\|\.py\)' -not -path "./.venv/*" -not -path "./__pycache__/*" -printf "%p %TY-%Tm-%Td %TH:%TM:%TS %Tz\n" | sort -n >".new_files"
75
76

            if [ -f ".current_files" ]; then
77
                if ! cmp -s ".new_files" ".current_files"; then
78
79
                    break
                fi
80
            fi
81
82
            
            cp ".new_files" ".current_files" &>/dev/null
83
84
85
        done

        if ./pid.sh >/dev/null; then
86
            ./start.sh 1>/dev/null
87
88
        fi
        ) &
89
90
    fi  

91
    tail ".main.log"
92
else
93
    >&2 echo "Invalid port $HTTP_PORT"
94
    exit 1
95
fi