#!/bin/sh
set -e

[ "$DEBUG" = "1" ] && set -x


#SERVER_ID=1919126762
#SERVER_SECRET="secret fa35a6e7a63093959cfc42ce7138f95f"
#RECEIVER="domain receiver.24mon.io"
#
# А в essm-conf.tpl они определяются. До будет просто произведена инсталяция
# Без редактирования конфига и запуска essm (хотя на debian/ubuntu запуск по умолчанию)

dist=""
dist_version=""
dist_version_family=""
dist_pretty=""
# Проверка если переменные выше не определены или пустые

check_required_vars() {
    if [ -z "$SERVER_ID" ] || [ -z "$SERVER_SECRET" ] || [ -z "$RECEIVER" ]; then
        return 1
    fi
    return 0
}

check_distro() {
    if [  -f /etc/os-release  ]; then
        dist=$(awk -F= '$1 == "ID" {gsub("\"", ""); print$2}' /etc/os-release)
        dist_version=$(awk -F= '$1 == "VERSION_ID" {gsub("\"", ""); print$2}' /etc/os-release)
        dist_pretty=$(awk -F= '$1 == "PRETTY_NAME" {gsub("\"", ""); print$2}' /etc/os-release)
    elif [ -f /etc/redhat-release ]; then
        dist=$(awk '{print tolower($1)}' /etc/redhat-release)
        dist_version=$(awk '{print tolower($3)}' /etc/redhat-release)
        dist_pretty=$(awk '{print$1" "$3}' /etc/redhat-release)
    elif [ $(uname -a | grep FreeBSD -c) -gt 0 ]; then
        echo "Freebsd?"
        dist=freebsd
        dist_version=$(uname -a | awk '{print $3}' |awk -F \. '{print $1}')
        dist_pretty=$(uname -a | awk '{print $1 " " $3}')        
    else
        cat <<-EOF

  Automated installation is not supported on distributions
  without /etc/os-release or /etc/redhat-release.

EOF
        exit 1
    fi

    dist=${dist?unable to determine the distribution}
    dist_version=${dist_version?unable to determine distribution version}
    dist_version_family=$(echo ${dist_version} | awk -F. '{print$1}')
    dist_version_family=${dist_version_family?failed to determine the distribution major number}
}

command_exists() {
  command -v "$@" > /dev/null 2>&1
}

not_supported() {
    cat <<-EOF

 ${dist_pretty} is not supported at this time.

 Scripted installation only supported on:
    CentOS 7 and later
    Debian 8 and later
    Ubuntu 16.04 and later

EOF
    exit 1
}

write_centos_repo() {
    $sh_c '
cat > /etc/yum.repos.d/ITSumma.repo <<"EOM"
[itsumma]
name=ITSumma
baseurl=http://repo2.itsumma.com/centos/$releasever/$basearch/
enabled=1
gpgkey=https://repo2.itsumma.com/itsumma.asc
gpgcheck=1
EOM

rpm --import https://repo2.itsumma.com/itsumma.asc
'
}

write_common_amzn_repo() {
    $sh_c '
cat > /etc/yum.repos.d/ITSumma.repo <<"EOM"
[itsumma]
name=ITSumma
baseurl=http://repo2.itsumma.com/centos/7/$basearch/
enabled=1
gpgkey=https://repo2.itsumma.com/itsumma.asc
gpgcheck=1
EOM

rpm --import https://repo2.itsumma.com/itsumma.asc
'
}

write_altlinux_repo() {
    $sh_c '
cat > /etc/apt/sources.list.d/itsumma.list <<"EOM"
rpm http://repo2.itsumma.com/centos/7/x86_64/ ./
EOM

curl -o /tmp/itsumma.asc https://repo2.itsumma.com/itsumma.asc

rpm --import /tmp/itsumma.asc
'
}

write_debian_repo() {
    $sh_c '
    export DEBIAN_FRONTEND=noninteractive
    apt-get -qqy update
    apt-get -y install apt-transport-https curl gnupg
    '
    repo_url="http://repo2.itsumma.com/debian";
    case "$dist:$dist_version_family" in
        debian:8) release="jessie" ;;
        debian:9) release="stretch" ;;
        debian:10) release="buster" ;;
        debian:11) release="bullseye" ;;
        debian:12) release="bookworm" ;;
        debian:13) release="trixie" ;;
    esac

    if [ "$dist_version_family" -ge 10 ]; then
        # Новый формат с signed-by
        $sh_c "curl -sSL ${repo_url%/*}/itsumma.gpg -o /usr/share/keyrings/itsumma.gpg"
        $sh_c "echo 'deb [signed-by=/usr/share/keyrings/itsumma.gpg] $repo_url $release main' > /etc/apt/sources.list.d/itsumma.list"
    else
        $sh_c "curl -sSL ${repo_url%/*}/itsumma.asc | apt-key add - || true"
        $sh_c "echo 'deb $repo_url $release main' > /etc/apt/sources.list.d/itsumma.list"
    fi
}

write_ubuntu_repo() {
    $sh_c '
    export DEBIAN_FRONTEND=noninteractive
    apt-get -qqy update
    apt-get -y install apt-transport-https curl gnupg
    '
    repo_url="http://repo2.itsumma.com/ubuntu";
    case "$dist:$dist_version_family" in
        ubuntu:16) release="xenial" ;;
        ubuntu:17) release="xenial" ;;
        ubuntu:18) release="bionic" ;;
        ubuntu:19) release="bionic" ;;
        ubuntu:20) release="focal" ;;
        ubuntu:22) release="jammy" ;;
        ubuntu:23) release="lunar" ;;
        ubuntu:24) release="noble" ;;
    esac

        $sh_c "curl -sSL ${repo_url%/*}/itsumma.gpg -o /usr/share/keyrings/itsumma.gpg"
        $sh_c "echo 'deb [signed-by=/usr/share/keyrings/itsumma.gpg] $repo_url $release main' > /etc/apt/sources.list.d/itsumma.list"
}

install_yum() {
    $sh_c 'yum install -y essm'
}

install_dnf() {
    $sh_c 'dnf install -y essm'
}

install_apt() {
    $sh_c '
apt-get -qqy update
apt-get -y install essm
'
}

install_freebsd() {
    $sh_c '
pkg add -f https://repo.itsumma.com/freebsd/essm/essm-0.4.8_1.txz
'
}

createConfig_freebsd() {
    echo "Generating config..."
    if [ ! -f /usr/local/etc/essm.conf ]; then
        cp /usr/local/etc/essm.conf.default /usr/local/etc/essm.conf
    fi
    sed -i '' "1i\\
id $SERVER_ID" /usr/local/etc/essm.conf
    sed -i '' "s/^secret INSERT_SECRET_HERE\$/$SERVER_SECRET/" /usr/local/etc/essm.conf
    sed -i '' "s/^domain INSERT_RECEIVER_DOMAIN_HERE\$/$RECEIVER/" /usr/local/etc/essm.conf
}

createConfig() {
    echo "Generating config..."
    sed -i "1i\id $SERVER_ID" /etc/essm.conf
    sed -i "s/^secret INSERT_SECRET_HERE\$/$SERVER_SECRET/" /etc/essm.conf
    sed -i "s/^domain INSERT_RECEIVER_DOMAIN_HERE\$/$RECEIVER/" /etc/essm.conf
}

essm_start() {
    echo "Starting essm..."
    if command_exists systemctl; then
        $sh_c 'systemctl enable --now essm 2>/dev/null || service essm start'
    elif command_exists service; then
        $sh_c 'service essm start'
    elif [ -f /etc/init.d/essm ]; then
        $sh_c '/etc/init.d/essm start'
    else
        echo "Warning: Could not start essm service" >&2
    fi
}

essm_install() {
    user="$(id -un 2>/dev/null || true)"

    sh_c='sh -c'
    if [ "$user" != 'root' ]; then
        if command_exists sudo; then
            sh_c='sudo -E sh -c'
        elif command_exists su; then
            sh_c='su -c'
        else
            cat >&2 <<-'EOF'
      Error: this installer needs the ability to run commands as root.
      We are unable to find either "sudo" or "su" available to make this happen.
EOF
            exit 1
        fi
    fi

    check_distro

    echo "Detected ${dist_pretty}..."

    case "$dist" in
        centos|redos|almalinux|rocky|rhel|ol)
            repo_func="write_centos_repo"
            install_func="install_yum"
            if [ "$dist_version_family" -ge 8 ]; then
                install_func="install_dnf"
            elif [ "$dist_version_family" -ge 7 ]; then
                install_func="install_yum"
            else
                not_supported
            fi
            ;;

        amzn|amzn2)
            repo_func="write_common_amzn_repo"
            install_func="install_yum"
            ;;

        fedora)
            [ "$dist_version_family" -ge 34 ] || not_supported
            repo_func="write_common_amzn_repo"
            install_func="install_yum"
            ;;

        debian)
            [ "$dist_version_family" -ge 8 ] || not_supported
            repo_func="write_debian_repo"
            install_func="install_apt"
            ;;
        ubuntu)
            [ "$dist_version_family" -ge 16 ] || not_supported
            repo_func="write_ubuntu_repo"
            install_func="install_apt"
            ;;
        altlinux)
            [ "$dist_version_family" -ge 8 ] || not_supported
            repo_func="write_altlinux_repo"
            install_func="install_apt"
            ;;
        freebsd)
            [ "$dist_version_family" -ge 10 ] || not_supported
            install_func="install_freebsd"
            ;;

        *)
            not_supported
            ;;
    esac

    $repo_func 2>/dev/null || true  # Для дистрибутивов без repo функции
    $install_func

    if check_required_vars; then
        case "$dist" in
            freebsd)
                createConfig_freebsd
                ;;
            *)
                createConfig
                ;;
        esac
        essm_start
        echo "ESSM installation and configuration completed successfully."
    else
        echo "The essm installation is completed without configuration."
        echo "Please perform the configuration manually."
    fi
}

essm_install

