#!/bin/sh

# Test that setuptools requirements are correct
# See #918683 for context of why we want this test

set -e

WORKDIR=$(mktemp -d)
trap "rm -rf $WORKDIR" 0 INT QUIT ABRT PIPE TERM
cd $WORKDIR

mkdir mypkg
mkdir mypkg/testlib
mkdir rundir3

cd mypkg

touch __init__.py

cat << EOF > setup.py
from setuptools import setup, find_packages

setup(name="testlib",
      version="0.0.1",
      description="Test sqlobject with setuptools requires",

      install_requires="SQLObject",
      packages=find_packages(),
      zip_safe=True,

      entry_points={
          'console_scripts': ['testdb=testlib.testdb:main'],
      },
)
EOF

cd testlib
cat << EOF > base.py
from sqlobject import SQLObject, IntCol

class TestCol(SQLObject):

    number = IntCol()
EOF

cat << EOF > testdb.py
import sys

from sqlobject import connectionForURI, sqlhub, SQLObjectNotFound

from testlib.base import TestCol


def run():
    sqlhub.processConnection = connectionForURI('sqlite:///:memory:')
    TestCol.createTable()
    entry1 = TestCol(number=1)

    # Check we have the right number of entries
    if TestCol.select().count() != 1:
        return False

    # check we can select by number

    entry = TestCol.selectBy(number=1).getOne()
    if entry != entry1:
        return False
    return True


def main():
    if not run():
        sys.exit(1)
EOF

# We are running pip as root for simplicity, and since this is
# a throwaway test container, the pip warning isn't applicable.
export PIP_ROOT_USER_ACTION=ignore

touch __init__.py

cd $WORKDIR
for py in $(py3versions -s) python3; do
   $py -m pip install --user --no-warn-script-location ./mypkg
   cd ~/.local/bin
   ./testdb
   cd $WORKDIR
   $py -m pip uninstall -y testlib
done
