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

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

# ============================================
# Helpers
# ============================================

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::symlink() {
  ln -sf /etc/wireguard/wgctl/wgctl /usr/local/bin/wgctl
}

function install::wgctl_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() {
  cp "${WGCTL_DIR}/install/ulogd.conf" /etc/ulogd.conf
  systemctl restart ulogd2
}

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

# ============================================
# Main
# ============================================

function install::main() {
  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!"
  echo "  Edit ${DATA_DIR}/wgctl.conf before first use."
}

install::main