#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2018 ScyllaDB
#

#
# This file is part of Scylla.
#
# Scylla is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Scylla is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Scylla.  If not, see <http://www.gnu.org/licenses/>.

import os
import sys
import tempfile
import tarfile
from scylla_util import *
import argparse

VERSION='1.0.1'
INSTALL_DIR=scylladir()+'/Prometheus/node_exporter'

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Download and install prometheus node_exporter')
    parser.add_argument('-F', '--force', action='store_true', default=False, help='Force re-installation when node_exporter is already installed')
    args = parser.parse_args()
    force = args.force
    if not is_nonroot() and os.getuid() > 0:
        print('Requires root permission.')
        sys.exit(1)
    node_exporter_p = bindir_p() / 'node_exporter'
    if node_exporter_p.exists() or (bindir_p() / 'prometheus-node_exporter').exists():
        if force:
            print('node_exporter already installed, reinstalling')
            try:
                node_exporter = systemd_unit('node-exporter.service')
                node_exporter.stop()
            except:
                pass
        else:
            print('node_exporter already installed, you can use `--force` to force reinstallation')
            sys.exit(1)

    if is_gentoo_variant():
        run('emerge -uq app-metrics/node_exporter')
        print('app-metrics/node_exporter does not install systemd service files, please fill a bug if you need them.')
        sys.exit(1)
    else:
        data = curl('https://github.com/prometheus/node_exporter/releases/download/v{version}/node_exporter-{version}.linux-amd64.tar.gz'.format(version=VERSION), byte=True)
        with open('/var/tmp/node_exporter-{version}.linux-amd64.tar.gz'.format(version=VERSION), 'wb') as f:
            f.write(data)
        with tarfile.open('/var/tmp/node_exporter-{version}.linux-amd64.tar.gz'.format(version=VERSION)) as tf:
            tf.extractall(INSTALL_DIR)
        os.remove('/var/tmp/node_exporter-{version}.linux-amd64.tar.gz'.format(version=VERSION))
        if node_exporter_p.exists():
            node_exporter_p.unlink()
        os.symlink('{install_dir}/node_exporter-{version}.linux-amd64/node_exporter'.format(install_dir=INSTALL_DIR, version=VERSION), str(node_exporter_p))
        node_exporter = systemd_unit('node-exporter.service')
        node_exporter.enable()
        node_exporter.start()

    print('node_exporter successfully installed')
