#!/usr/bin/env python

# Copyright 2019 Imply Data, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import sys

try:
  # Python 3
  from urllib.request import urlopen
  from urllib.request import Request
except ImportError:
  # Python 2
  from urllib2 import urlopen
  from urllib2 import Request


VERSION_FILE = "dist/resources/imply.version"
VERSION_URL = "https://static.imply.io/release/LATEST.txt"
TIMEOUT = 1

def get_version_from_file(file_name):
  try:
    with open(file_name, 'r') as f:
      return str(f.read().strip())
  except:
    return None

def get_version_from_url(url):
  try:
    req = Request(url)
    response = urlopen(req, None, TIMEOUT)
    return str(response.read().strip())
  except:
    return None

def compare_versions(a, b):
  version_regex = r'^(\d+)\.(\d+)\.(\d+)(?:-.*|)$'
  amatch = re.match(version_regex, a)
  bmatch = re.match(version_regex, b)

  if amatch and bmatch:
    amajor = int(amatch.group(1))
    aminor = int(amatch.group(2))
    asubminor = int(amatch.group(3))

    bmajor = int(bmatch.group(1))
    bminor = int(bmatch.group(2))
    bsubminor = int(bmatch.group(3))

    if cmp(amajor, bmajor):
      return cmp(amajor, bmajor)
    elif cmp(aminor, bminor):
      return cmp(aminor, bminor)
    else:
      return cmp(asubminor, bsubminor)
  else:
    return 0

def main():
  version_from_file = get_version_from_file(VERSION_FILE)
  if version_from_file is None:
    sys.stderr.write('Unable to check for new versions, version file is missing: ' + VERSION_FILE + '\n')
    return

  version_from_url = get_version_from_url(VERSION_URL)
  if version_from_url is None:
    return

  if compare_versions(version_from_url, version_from_file) > 0:
    sys.stderr.write('\033[1m' + 'New version available: ' + version_from_url + ', you have: ' + version_from_file + '\033[0m' + '\n')

try:
  main()
except:
  pass
