#!/usr/bin/env bash

set -e

# local variables
TEST_LIBRARY=Encrypted
TEST_LIBRARY_PASSWORD=SecretKey

# environment variables passed on docker-compose
export NAME=seafileencrypted
export MYSQL_ROOT_PASSWORD=pixenij4zacoguq0kopamid6
export SEAFILE_ADMIN_EMAIL=seafile@rclone.org
export SEAFILE_ADMIN_PASSWORD=pixenij4zacoguq0kopamid6
export SEAFILE_IP=127.0.0.1
export SEAFILE_PORT=8088
export SEAFILE_TEST_DATA=${SEAFILE_TEST_DATA:-/tmp/seafile-test-data}
# Seafile 12 and later are not published under the `latest` tag (that stops at 11.x)
export SEAFILE_VERSION=${SEAFILE_VERSION:-13.0-latest}
# Seafile 12 and later need a JWT key (only used by this throwaway test server)
export SEAFILE_JWT_PRIVATE_KEY=ngirojohevaqaxuyobolaxakopelicok

# make sure the data directory exists
mkdir -p ${SEAFILE_TEST_DATA}/${NAME}

# docker compose project directory
COMPOSE_DIR=$(dirname "$0")/seafile

compose() {
    docker compose --project-directory ${COMPOSE_DIR} --project-name ${NAME} --file ${COMPOSE_DIR}/docker-compose.yml "$@"
}

wait_for_seafile() {
    # the web server answers before Seahub has been initialised, so wait for the API to respond
    seafile_endpoint="http://${SEAFILE_IP}:${SEAFILE_PORT}/api2/ping/"
    wait_seconds=1
    echo -n "Waiting for Seafile server to start"
    for iterations in `seq 1 180`;
    do
      if curl -s -L "$seafile_endpoint" | grep -q pong; then
        echo
        break
      fi
      echo -n "."
      sleep $wait_seconds
    done
}

start() {
    compose up -d

    wait_for_seafile

    # Seahub throttles anonymous API calls, which includes logging in,
    # to 60/minute. Concurrent test runs exceed that so raise it.
    # seahub_settings.py is only created on first start.
    settings=/shared/seafile/conf/seahub_settings.py
    if ! compose exec -T seafile grep -q DEFAULT_THROTTLE_RATES $settings; then
        compose exec -T seafile sh -c "cat >> $settings" <<'EOF'
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'ping': '3000/minute',
        'anon': '100000/minute',
        'user': '100000/minute',
        'share_link_zip_task': '10/minute'
    },
    'UNICODE_JSON': False,
}
EOF
        # Seahub may still be starting up so retry if the restart fails
        for iterations in `seq 1 10`;
        do
          if compose exec -T seafile /opt/seafile/seafile-server-latest/seahub.sh restart >/dev/null; then
            break
          fi
          sleep 3
        done
        wait_for_seafile
    fi

    # the admin user may not be set up yet when the API first answers
    # authentication token answer should be like: {"token":"dbf58423f1632b5b679a13b0929f1d0751d9250c"}
    TOKEN=
    for iterations in `seq 1 60`;
    do
      TOKEN=`curl --silent \
          --data-urlencode username=${SEAFILE_ADMIN_EMAIL} -d password=${SEAFILE_ADMIN_PASSWORD} \
          http://${SEAFILE_IP}:${SEAFILE_PORT}/api2/auth-token/ \
          | sed -n 's/^{"token":"\(.*\)"}$/\1/p' || true`
      if [ -n "${TOKEN}" ]; then
        break
      fi
      sleep 1
    done

    # create encrypted library
    curl --silent -o /dev/null -X POST -d "name=${TEST_LIBRARY}&passwd=${TEST_LIBRARY_PASSWORD}" -H "Authorization: Token ${TOKEN}" "http://${SEAFILE_IP}:${SEAFILE_PORT}/api2/repos/"

    echo _connect=${SEAFILE_IP}:${SEAFILE_PORT}
    echo type=seafile
    echo url=http://${SEAFILE_IP}:${SEAFILE_PORT}/
    echo user=${SEAFILE_ADMIN_EMAIL}
    echo pass=$(rclone obscure ${SEAFILE_ADMIN_PASSWORD})
    echo library=${TEST_LIBRARY}
    echo library_key=$(rclone obscure ${TEST_LIBRARY_PASSWORD})
}

stop() {
    if status ; then
        compose down
    fi
}

status() {
    if [ -n "$(compose ps --status running --quiet 2>/dev/null)" ] ; then
        echo "$NAME running"
    else
        echo "$NAME not running"
        return 1
    fi
    return 0
}

. $(dirname "$0")/run.bash
