#!/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"
    cmd = (
        "{} ls-remote --refs --tags {} | "
        "cut -d '/' -f 3 | "
        # "tr '-' '~'  | "
        "sort --version-sort | "
        "tail -1".format(git, repository)
    )
    p = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        universal_newlines=True,
        shell=True,
    )
    out, err = p.communicate()
    if err:
        print("ERROR: {}".format(err))
        sys.exit(1)
    latest_release = out.strip()
    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:])
