#!/bin/sh

###Download and install Zabbix Proxy, SQL scripts, and uuidgen
curl -o /dos/zabbix.deb https://repo.zabbix.com/zabbix/7.0/debian/pool/main/z/zabbix-release/zabbix-release_7.0-2+debian12_all.deb >> /dos/log 2>&1
dpkg -i /dos/zabbix.deb
apt update
apt install zabbix-proxy-sqlite3 zabbix-sql-scripts zabbix-agent2 uuid-runtime -y

###Zabbix variables
ZABBIX_PROXY_UUID=$(uuidgen)
ZABBIX_AGENT_UUID=$(uuidgen)
ZABBIX_PSK_UUID=$(uuidgen)
ZABBIX_PSK=$(openssl rand -hex 32) 
LOCAL_ADDRESS=$(grep -oP '(?<=domain ).*' /etc/resolv.conf)


##Create Databse
mkdir -p /etc/zabbix/db
cat /usr/share/zabbix-sql-scripts/sqlite3/proxy.sql | sqlite3 /etc/zabbix/db/zabbix.db
chown zabbix:zabbix /etc/zabbix/db -R

###Create PSK
echo $ZABBIX_PSK > /etc/zabbix/zabbix.psk
chmod 400 /etc/zabbix/zabbix.psk
chown zabbix:zabbix /etc/zabbix/zabbix.psk

###Edit Proxy Configuration
#Server settings
sed -i "s/^Server=127\.0\.0\.1/Server=zabbix.digital-origin.co.uk/g" /etc/zabbix/zabbix_proxy.conf
#Hostname
sed -i "s/^Hostname=Zabbix proxy/Hostname=$ZABBIX_PROXY_UUID/g" /etc/zabbix/zabbix_proxy.conf
#DBName
sed -i "s/^DBName=zabbix_proxy/DBName=\/etc\/zabbix\/db\/zabbix\.db/g" /etc/zabbix/zabbix_proxy.conf
#TLSConnect
sed -i "s/^# TLSConnect=unencrypted/TLSConnect=psk/g" /etc/zabbix/zabbix_proxy.conf
#TLSPSKIdentity
sed -i "s/^# TLSPSKIdentity=/TLSPSKIdentity=$ZABBIX_PSK_UUID/g" /etc/zabbix/zabbix_proxy.conf
#TLSPSKFile
sed -i "s/^# TLSPSKFile=/TLSPSKFile=\/etc\/zabbix\/zabbix\.psk/g" /etc/zabbix/zabbix_proxy.conf

###Edit Agent Configuration
#Server settings
sed -i "s/^Server=127\.0\.0\.1/Server=127.0.0.1,zabbix.digital-origin.co.uk/g" /etc/zabbix/zabbix_agent2.conf
#ServerActive settings
sed -i "s/^ServerActive=127\.0\.0\.1/ServerActive=127.0.0.1,zabbix.digital-origin.co.uk/" /etc/zabbix/zabbix_agent2.conf
#Hostname
sed -i "s/^Hostname=Zabbix server/Hostname=$ZABBIX_AGENT_UUID/g" /etc/zabbix/zabbix_agent2.conf

###Enable service
systemctl enable --now zabbix-proxy
systemctl enable --now zabbix-agent2

###Register with Zabbix server
ZABBIX_API_CREDENTIALS=$(base64 -i -d /dos/zabbix.credential)

echo $ZABBIX_API_CREDENTIALS >> /dos/zabbixcredentials.log

ZABBIX_API_KEY_RESPONSE=$(curl --location 'https://zabbix.digital-origin.co.uk/api_jsonrpc.php' \
--header 'Content-Type: application/json' \
--data "{
    \"id\": 1,
    \"jsonrpc\": \"2.0\",
    \"method\": \"user.login\",
    \"params\": {
        \"username\": \"$(expr "$ZABBIX_API_CREDENTIALS" : '\(.*\):.*')\",
        \"password\": \"$(expr "$ZABBIX_API_CREDENTIALS" : '.*:\(.*\)')\"
    }
}") >> /dos/zabbixcurl.log 2>&1
echo $ZABBIX_API_KEY_RESPONSE >> /dos/zabbixcurl.log
ZABBIX_API_KEY=$(echo $ZABBIX_API_KEY_RESPONSE | jq -r '.result') >> /dos/zabbixcurl.log 2>&1

echo $ZABBIX_API_KEY >> /dos/zabbixcurl.log

curl --location 'https://zabbix.digital-origin.co.uk/api_jsonrpc.php' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $ZABBIX_API_KEY" \
--data "{
    \"id\": 1,
    \"jsonrpc\": \"2.0\",
    \"method\": \"proxy.create\",
    \"params\": {
        \"name\": \"$ZABBIX_PROXY_UUID\",
        \"operating_mode\": 0,
        \"description\": \"[customer:Someone]\r\n[local_address:zabbixmonitor.$LOCAL_ADDRESS]\",
        \"tls_accept\": 2,
        \"tls_psk_identity\": \"$ZABBIX_PSK_UUID\",
        \"tls_psk\": \"$ZABBIX_PSK\"
    }
}" >> /dos/zabbixcurl.log 2>&1
# Grab the proxy ID from the response
ZABBIX_PROXY_ID=$(grep -oP '(?<="proxyids":\[")[^"]+' /dos/zabbixcurl.log | tail -1)

# Create the agent host
curl --location 'https://zabbix.digital-origin.co.uk/api_jsonrpc.php' \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $ZABBIX_API_KEY" \
--data "{
    \"id\": 1,
    \"jsonrpc\": \"2.0\",
    \"method\": \"host.create\",
    \"params\": {
        \"host\": \"$ZABBIX_AGENT_UUID\",
        \"name\": \"New Zabbix Proxy - $ZABBIX_AGENT_UUID\",
        \"interfaces\": [
            {
                \"type\": 1,
                \"main\": 1,
                \"useip\": 1,
                \"ip\": \"127.0.0.1\",
                \"dns\": \"\",
                \"port\": \"10050\"
            }
        ],
        \"groups\": [
            {
                \"groupid\": \"2\"
            }
        ],
        \"templates\": [
            {
                \"templateid\": \"10343\"
            }
        ],
        \"monitored_by\": \"1\",
        \"proxyid\": \"$ZABBIX_PROXY_ID\"
    }
}" >> /dos/zabbixcurl.log 2>&1

###Install and Configure Tailscale
#Add Tailscale's package signing key and repository
curl -fsSL https://pkgs.tailscale.com/stable/debian/bookworm.noarmor.gpg | tee /usr/share/keyrings/tailscale-archive-keyring.gpg >/dev/null
curl -fsSL https://pkgs.tailscale.com/stable/debian/bookworm.tailscale-keyring.list | tee /etc/apt/sources.list.d/tailscale.list

#Install Tailscale
apt update
apt install tailscale -y

#Enable and start Tailscale service
systemctl enable --now tailscaled
sleep 15

###Configure Tailscale with OAuth
TAILSCALE_AUTHKEY=$(base64 -i -d /dos/tailscale.credential)

#Enable IP forwarding
echo 'net.ipv4.ip_forward = 1' | tee -a /etc/sysctl.d/99-tailscale.conf >> /dos/tailscale.log 2>&1
echo 'net.ipv6.conf.all.forwarding = 1' | tee -a /etc/sysctl.d/99-tailscale.conf >> /dos/tailscale.log 2>&1
sysctl -p /etc/sysctl.d/99-tailscale.conf >> /dos/tailscale.log 2>&1

#Defer Tailscale login to first boot (systemd not running in installer)
cat >/usr/local/sbin/tailscale-firstboot.sh <<EOF
#!/bin/sh
TAILSCALE_AUTHKEY=\$(base64 -i -d /dos/tailscale.credential)
if [ -z "\$TAILSCALE_AUTHKEY" ]; then
  echo "No Tailscale auth key found" >> /dos/tailscale.log
  exit 1
fi
/usr/bin/tailscale up --authkey="\$TAILSCALE_AUTHKEY" --ssh --advertise-tags=tag:zabbix-proxy --advertise-exit-node --hostname="$ZABBIX_PROXY_UUID" >> /dos/tailscale.log 2>&1
EOF
chmod 700 /usr/local/sbin/tailscale-firstboot.sh

cat >/etc/systemd/system/tailscale-firstboot.service <<EOF
[Unit]
Description=Run tailscale up on first boot
After=network-online.target tailscaled.service
Wants=network-online.target tailscaled.service

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/tailscale-firstboot.sh
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
EOF

systemctl enable tailscale-firstboot.service