#!/usr/bin/env python3

import argparse
import os
import re
import stat
import subprocess
import urllib.request

parser = argparse.ArgumentParser(description="Build the project,")
parser.add_argument("--config", action="store_true", help="Build only the configuration image")
parser.add_argument("--geoportal", action="store_true", help="Build only the geoportal image")
parser.add_argument("--env", action="store_true", help="Force to create the `.env` file")
parser.add_argument("--pgschema", default="main", help="The main schema name used in PostgreSQL")
parser.add_argument("--upgrade", help="Start upgrading the project to version")
parser.add_argument("env_files", default=['env.sample'], nargs="*", help="The environment files")

args = parser.parse_args()

if args.upgrade:
    version_re = re.search(r"([0-9]\.[0-9])\.[0-9]", args.upgrade)
    major_version = version_re.group(0) if version_re is not None else args.upgrade
    full_version = args.upgrade if args.upgrade != "master" else "{{geomapfish_main_version}}"
    with open("upgrade", "w") as f:
        result = urllib.request.urlopen(
            "https://raw.githubusercontent.com/camptocamp/c2cgeoportal/{}/scripts/upgrade".format(
                major_version
            )
        )
        if result.code != 200:
            print("ERROR:")
            print(result.read())
            exit(1)
        f.write(result.read().decode())
    os.chmod("upgrade", os.stat("upgrade").st_mode | stat.S_IXUSR)
    try:
        subprocess.check_call(["./upgrade", full_version])
    except subprocess.CalledProcessError:
        exit(1)
    exit(0)

auto = not (args.config or args.geoportal or args.env)
env = {}
for env_file in args.env_files:
    with open(env_file) as f:
        for line in f:
            if line and line[0] != '#':
                try:
                    index = line.index('=')
                    env[line[:index].strip()] = line[index+1:].strip()
                except ValueError:
                    # Ignore lines that don't have a '='
                    pass

tag = ":" + env['DOCKER_TAG'] if 'DOCKER_TAG' in env else ""

if auto or args.config:
    subprocess.check_call(
        ["docker", "build", "--tag=camptocamp/{{package}}-config" + tag, "--build-arg=PGSCHEMA=" + args.pgschema, "."]
    )
if auto or args.geoportal:
    git_hash = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip().decode()
    subprocess.check_call(
        [
            "docker",
            "build",
            "--tag=camptocamp/{{package}}-geoportal" + tag,
            "--build-arg=PGSCHEMA=" + args.pgschema,
            "--build-arg=GIT_HASH=" + git_hash,
            "geoportal",
        ]
    )
    subprocess.check_call(
        [
            "docker",
            "build",
            "--target=builder",
            "--tag=camptocamp/{{package}}-geoportal-dev" + tag,
            "--build-arg=PGSCHEMA=" + args.pgschema,
            "--build-arg=GIT_HASH=" + git_hash,
            "geoportal",
        ]
    )

if args.env or auto and not os.path.exists(".env"):
    with open(".env", "w") as dest:
        env_files = args.env_files if args.env_files else [".env.sample"]
        for file_ in env_files:
            print("Use env file: " + file_)
            with open(file_) as src:
                dest.write(src.read())
