#!/usr/bin/env bash
set -e

WGCTL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DATA_DIR="/etc/wireguard/.wgctl"

echo "Installing wgctl..."

install::dependencies
install::make_structure
install::daemon_logs
install::symlink
install::wgctl_service
install_ulogd
install::create_config

echo "wgctl installed successfully!"

function install::symlink() {
  ln -sf /etc/wireguard/wgctl/wgctl /usr/local/bin/wgctl
}

function install::dependencies() {
  apt install -y wireguard ulogd2 ulogd2-json python3 qrencode
}

function install::make_structure() {
  mkdir -p "${DATA_DIR}"/{rules,groups,blocks,meta,daemon}
}

function install::daemon_logs() {
  touch "${DATA_DIR}/daemon/fw_events.log"
  chown ulog:ulog "${DATA_DIR}/daemon/fw_events.log"

  echo '{}' > "${DATA_DIR}/daemon/watchlist.json"
  echo '{}' > "${DATA_DIR}/daemon/endpoint_cache.json"
}

function install::wgctl_service() {
  # Install systemd service
  cp "${WGCTL_DIR}/install/wgctl-monitor.service" /etc/systemd/system/
  systemctl daemon-reload
  systemctl enable wgctl-monitor
  systemctl start wgctl-monitor
}

function install::ulogd() {
  # Install ulogd config
  cp "${WGCTL_DIR}/install/ulogd.conf" /etc/ulogd.conf
  systemctl restart ulogd2
}

function install::create_config() {
  if [[ ! -f "${DATA_DIR}/wgctl.conf" ]]; then
    install::create_example_config
    cp "${WGCTL_DIR}/install/wgctl.conf.example" "${DATA_DIR}/wgctl.conf"
    echo "  Created ${DATA_DIR}/wgctl.conf — edit with your settings"
  fi
}

function install::create_example_config() {
cat > /etc/wireguard/wgctl/install/wgctl.conf.example << 'EOF'
# wgctl configuration
# Copy to /etc/wireguard/.wgctl/wgctl.conf and edit

WG_INTERFACE=wg0
WG_ENDPOINT=wg.yourdomain.com:51820
WG_DNS=10.0.0.103
WG_LISTEN_PORT=51820
WG_SUBNET=10.1.0.0/16
WG_LAN=10.0.0.0/24
EOF
}