#!/bin/sh

set -e

INSTALL_DIR="/usr/bin"
CONFIG_DIR="/etc/dnsproxy"
SERVICE_DIR="/etc/systemd/system"

# Temporary directory for download and extraction
TMP_DIR=$(mktemp -d)

# Function to clean up temporary directory on exit
cleanup() {
    echo "Cleaning up temporary files..."
    rm -rf "$TMP_DIR"
}
trap cleanup EXIT

# Detect OS and Architecture
OS=$(uname | tr '[:upper:]' '[:lower:]')
ARCH=$(uname -m)
case $ARCH in
    x86_64) ARCH="amd64" ;;
    i386) ARCH="386" ;;
    aarch64) ARCH="arm64" ;;
    armv7l) ARCH="arm7" ;;
    armv6l) ARCH="arm6" ;;
    armv5*) ARCH="arm5" ;;
    arm*) ARCH="arm" ;;
    *) echo "Architecture $ARCH is not supported by this script."; exit 1 ;;
esac

# Fetch latest release URL from GitHub API
echo "Fetching the latest release URL for $OS architecture $ARCH..."
RELEASE_JSON=$(curl -s https://api.github.com/repos/AdguardTeam/dnsproxy/releases/latest)
URL=$(echo "$RELEASE_JSON" | grep "browser_download_url" | grep "$OS-$ARCH" | cut -d '"' -f 4)

if [ -z "$URL" ]; then
    echo "Failed to find a download URL for dnsproxy."
    exit 1
fi

echo "Downloading dnsproxy from $URL..."
curl -L "$URL" -o "$TMP_DIR/dnsproxy.tar.gz"

echo "Extracting dnsproxy..."
tar -xz -C "$TMP_DIR" -f "$TMP_DIR/dnsproxy.tar.gz"

# Debug: List the contents of the temporary directory
echo "Contents of the temporary directory:"
ls -l "$TMP_DIR"

# Find the extracted binary
BINARY_PATH=$(find "$TMP_DIR" -type f -name 'dnsproxy')
if [ ! -f "$BINARY_PATH" ]; then
    echo "Error: dnsproxy binary not found after extraction."
    exit 1
fi

echo "Installing dnsproxy to $INSTALL_DIR..."
sudo mv "$BINARY_PATH" "$INSTALL_DIR/dnsproxy"
sudo chmod +x "$INSTALL_DIR/dnsproxy"

echo "Setting up configuration directory at $CONFIG_DIR..."
sudo mkdir -p "$CONFIG_DIR"

# Configuration file for dnsproxy
echo "Creating configuration file..."
sudo tee "$CONFIG_DIR/config.yaml" > /dev/null << EOF
bootstrap:
  - "1.1.1.1:53"
listen-addrs:
  - "127.0.0.1"
listen-ports:
  - 1053
max-go-routines: 0
ratelimit: 0
ratelimit-subnet-len-ipv4: 24
ratelimit-subnet-len-ipv6: 64
udp-buf-size: 0
upstream:
  - "https://1.1.1.1/dns-query"
timeout: '10s'
EOF

# Systemd service file for dnsproxy
echo "Creating systemd service file..."
sudo tee "$SERVICE_DIR/dnsproxy.service" > /dev/null << EOF
[Unit]
Description=DNS Proxy
After=network.target
Requires=network.target

[Service]
Type=simple
ExecStart=$INSTALL_DIR/dnsproxy --config-path=$CONFIG_DIR/config.yaml
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

echo "Reloading systemd daemon..."
sudo systemctl daemon-reload
sudo systemctl enable dnsproxy.service
sudo systemctl start dnsproxy.service

# Display configuration file content
echo "dnsproxy configuration file content:"
cat "$CONFIG_DIR/config.yaml"

echo "dnsproxy has been successfully installed and started."