#!/bin/env python3
#
# 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.

from pathlib import Path
import os
import tempfile
import sys
import subprocess


def locate_bsc(base: Path) -> Path:
    bsc = base / "node_modules" / ".bin" / "bsc"
    if bsc.exists():
        return bsc
    if base == base.parent:
        raise RuntimeError("Could not find bsc")
    return locate_bsc(base.parent)


def main() -> None:
    bsc = locate_bsc(Path(os.getcwd()))
    content = sys.stdin.read()
    res = 1
    with tempfile.NamedTemporaryFile(suffix=".res", mode="w", delete=False) as fp:
        fp.write(content)
        fp.close()
        proc = subprocess.Popen([str(bsc), "-format", fp.name], stdout=subprocess.PIPE)
        formatted, _ = proc.communicate()
        formatted_str = formatted.decode("utf-8")
        if formatted_str != content:
            res = 0
            print(formatted_str)
        os.unlink(fp.name)
    sys.exit(res)


if __name__ == "__main__":
    main()
