#!/bin/bash
set -e

os_detect() {
    OSTYPE=unknown
    if [ -f /etc/redhat-release ]; then
        # RH family
        export OSTYPE=REDHAT
    elif [ -f /etc/debian_version ]; then
        # DEB family
        export OSTYPE=DEBIAN
    fi
}

redhat_open_port() {
    echo "Open 10050 tcp port"
    if command -v firewall-cmd &>/dev/null; then
        firewall-cmd --zone=public --add-port=10050/tcp --permanent
    else
        iptables -A INPUT -p tcp --dport 10050 -j ACCEPT
        iptables -A OUTPUT -p tcp --dport 10050 -j ACCEPT
    fi
}

debian_open_port() {
    echo "Open 10050 tcp port"
    ufw allow 10050/tcp 2>/dev/null
}

function net_downloader {
    # $1 res_scr
    # $2 res_dst
    if command -v curl &>/dev/null; then
        curl -s $1 -o $2
    elif command -v wget &>/dev/null; then
        wget $1 -O $2
    else
        echo "Install curl or wget before runing the script"
        exit 1
    fi
}



os_detect

case ${OSTYPE} in
    REDHAT)
        grep -qi "fedora" /etc/redhat-release && OSNAME="fedora" || OSNAME="centos"
        cat <<EOF > /etc/yum.repos.d/timeweb-zabbix.repo
[timeweb-zabbix]
name=Zabbix Agent From Timeweb
baseurl=http://zabbix.repo.timeweb.ru/$OSNAME/\$releasever/zabbix/x86_64/
gpgkey=http://zabbix.repo.timeweb.ru/public.gpg
gpgcheck=1
repo_gpgcheck=0
enabled=1
skip_if_unavailable=1
EOF
        yum --disablerepo='*' --enablerepo='timeweb-zabbix' makecache
        yum -y install zabbix-agent-timeweb
        redhat_open_port
;;
    DEBIAN)
        (umask 0022 && net_downloader http://zabbix.repo.timeweb.ru/timeweb-zabbix.gpg /etc/apt/trusted.gpg.d/timeweb-zabbix.gpg)
        CODENAME=$(lsb_release -sc)
        if [ $CODENAME = "hirsute" ] || [ $CODENAME = "jammy" ]; then
            CODENAME="focal"
        fi
        echo "deb [arch=amd64] http://zabbix.repo.timeweb.ru/$(lsb_release -si | tr '[:upper:]' '[:lower:]')/ $CODENAME main" > /etc/apt/sources.list.d/timeweb-zabbix.list
        apt-get -qq update
        apt-get install zabbix-agent-timeweb --yes
        debian_open_port
;;
esac
echo "Done"
