#!/usr/bin/env python3
import shutil
import subprocess
import sys

from SCRIdb.query import main
from SCRIdb.version import __version__


if __name__ == "__main__":
    # check latest version
    git = shutil.which("git")
    repository = "https://github.com/dpeerlab/SCRI_db"
    out = subprocess.Popen(
        "{} ls-remote -t --refs '{}' | tail -1".format(git, repository),
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        shell=True,
    )
    out, err = out.communicate()
    if err:
        print("ERROR: {}".format(err))
        sys.exit(1)
    latest_release = out.split()[-1].split("/")[-1]
    instructions = (
        ">>> pip install -U SCRIdb\n\t>>> scridb -v"
    )
    assert latest_release == __version__, (
        "Please install the latest `SCRI_db` release: {}. Follow these "
        "steps:\n\t{}".format(latest_release, instructions)
    )
    print("You are using the latest version '{0:5}' {1:>5}!".format(__version__, "OK"))
    main(sys.argv[1:])
