#!/bin/bash
# Copyright (c) 2024 Husarnet sp. z o.o.
set -eu

repo_url="https://nightly.husarnet.com"
repo_key_id="197D62F68A4C7BD6"

deb_repo="""\
deb [signed-by=/usr/share/keyrings/husarnet.gpg] ${repo_url}/deb/ all husarnet
"""

rpm_repo="""\
[husarnet]
name=Husarnet
baseurl=${repo_url}/rpm/
enabled=1
skip_if_unavailable=1
gpgcheck=1
gpgkey=${repo_url}/repo.key
"""

pacman_repo="""\
[husarnet]
SigLevel = PackageRequired
Server = ${repo_url}/pacman/\$arch
"""

echo "========================================"
echo "Installing Husarnet from ${repo_url}"
echo "========================================"

install_yum() {
    yum install -y curl

    rpm --import ${repo_url}/repo.key

    echo "${rpm_repo}" >/etc/yum.repos.d/husarnet.repo

    yum install -y husarnet
}

install_deb() {
    apt-get install -y curl apt-transport-https ca-certificates gnupg

    # This is the old method
    if apt-key list | grep 'husarnet' >/dev/null; then
        apt-key del husarnet
        apt-key del ${repo_key_id}
    fi
    curl ${repo_url}/repo.key | apt-key add -

    # This is the new method
    curl ${repo_url}/repo.gpg >/usr/share/keyrings/husarnet.gpg

    # Install actual repo
    echo "${deb_repo}" >/etc/apt/sources.list.d/husarnet.list

    apt-get update --allow-releaseinfo-change || true
    apt-get install -y husarnet
}

install_pacman() {
    pacman --noconfirm -Syy
    pacman --noconfirm -S curl

    curl -s ${repo_url}/repo.key | pacman-key --add -

    pacman-key --init
    pacman-key --lsign-key ${repo_key_id}

    if ! grep -F "[husarnet]" /etc/pacman.conf >/dev/null; then
        echo "${pacman_repo}" >>/etc/pacman.conf
    fi

    pacman --noconfirm -Syy
    pacman --noconfirm -S husarnet
}

enable_service() {
    if ! systemctl >/dev/null; then
        echo "========================================"
        echo "You are not running systemd, we will not automatically add a service."
        echo ""
        echo "Please make sure 'husarnet-daemon' (or husarnet-docker) is executed at system startup."
        echo "========================================"
    else
        systemctl daemon-reload
        systemctl enable husarnet
        systemctl start husarnet
    fi
}

if [ "$(id -u)" != 0 ]; then
    echo "Error: please run the installer as root."
    exit 1
fi

if apt-get --version >/dev/null 2>/dev/null; then
    install_deb
elif yum --version >/dev/null 2>/dev/null; then
    install_yum
elif pacman -V --version >/dev/null 2>/dev/null; then
    install_pacman
else
    echo "Currently only apt-get/yum/pacman based distributions are supported by this script."
    echo "Please follow manual installation method on https://docs.husarnet.com/install/"
    exit 1
fi

enable_service

echo "========================================"
echo "Husarnet installed successfully"
echo "========================================"
