# SPDX-FileCopyrightText: 2020 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ config, depot, pkgs, ... }:
let
  inherit (depot.ops) secrets;

  netbox = depot.nix.pkgs.netbox.override {
    configuration = ''
      ALLOWED_HOSTS = ["netbox.int.lukegb.com"]
      DATABASE = {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'netbox',
      }

      REDIS = {
        'tasks': {
          'HOST': 'localhost',
          'PORT': 6379,
          'DATABASE': 0,
          'SSL': False,
        },
        'caching': {
          'HOST': 'localhost',
          'PORT': 6379,
          'DATABASE': 1,
          'SSL': False,
        },
      }

      SECRET_KEY = '${secrets.netbox.secretKey}'

      ADMINS = []
      ALLOWED_URL_SCHEMES = (
        'file', 'ftp', 'ftps', 'http', 'https', 'irc', 'mailto', 'sftp', 'ssh', 'tel', 'telnet', 'tftp', 'vnc', 'xmpp',
      )

      BANNER_TOP = ""
      BANNER_BOTTOM = ""
      BANNER_LOGIN = ""
      BASE_PATH = ""

      CHANGELOG_RETENTION = 0

      CORS_ORIGIN_ALLOW_ALL = False
      CORS_ORIGIN_WHITELIST = []
      CORS_ORIGIN_REGEX_WHITELIST = []

      CUSTOM_VALIDATORS = {}

      DEBUG = False

      EMAIL = {}

      ENFORCE_GLOBAL_UNIQUE = True

      EXEMPT_VIEW_PERMISSIONS = []

      GRAPHQL_ENABLED = False

      INTERNAL_IPS = ('127.0.0.1', '::1')

      LOGGING = {}

      LOGIN_REQUIRED = True
      LOGIN_TIMEOUT = None

      MAINTENANCE_MODE = False

      MAPS_URL = 'https://maps.google.com/?q='

      MAX_PAGE_SIZE = 1000

      MEDIA_ROOT = '/srv/netbox/media'

      STORAGE_BACKEND = 'storages.backends.s3boto3.S3Boto3Storage'
      STORAGE_CONFIG = {
        'AWS_ACCESS_KEY_ID': "${secrets.netbox.s3.accessKey}",
        'AWS_SECRET_ACCESS_KEY': "${secrets.netbox.s3.secretAccessKey}",
        'AWS_STORAGE_BUCKET_NAME': 'netbox',
        'AWS_S3_ENDPOINT_URL': 'https://objdump.zxcvbnm.ninja',
        'AWS_S3_REGION_NAME': 'london',
      }

      METRICS_ENABLED = False

      NAPALM_USERNAME = ""
      NAPALM_PASSWORD = ""
      NAPALM_TIMEOUT = 30
      NAPALM_ARGS = {}

      PAGINATE_COUNT = 50

      PLUGINS = []

      PREFER_IPV4 = False

      RACK_ELEVATION_DEFAULT_UNIT_HEIGHT = 22
      RACK_ELEVATION_DEFAULT_UNIT_WIDTH = 220

      REMOTE_AUTH_ENABLED = False
      REMOTE_AUTH_BACKEND = 'netbox.authentication.RemoteUserBackend'
      REMOTE_AUTH_HEADER = 'HTTP_REMOTE_USER'
      REMOTE_AUTH_AUTO_CREATE_USER = True
      REMOTE_AUTH_DEFAULT_GROUPS = []
      REMOTE_AUTH_DEFAULT_PERMISSIONS = {}

      RELEASE_CHECK_URL = None

      REPORTS_ROOT = '/srv/netbox/reports'

      RQ_DEFAULT_TIMEOUT = 300

      SCRIPTS_ROOT = '/srv/netbox/scripts'

      SESSION_COOKIE_NAME = 'netboxsess'

      TIME_ZONE = 'UTC'

      DATE_FORMAT = 'Y-m-d'
      SHORT_DATE_FORMAT = 'Y-m-d'
      TIME_FORMAT = 'g:i a'
      SHORT_TIME_FORMAT = 'H:i:s'
      DATETIME_FORMAT = 'Y-m-d g:i a'
      SHORT_DATETIME_FORMAT = 'Y-m-d H:i'
    '';
  };
in {
  imports = [
    ../lib/bvm.nix
  ];

  # Networking!
  networking = {
    hostName = "bvm-netbox";
    hostId = "e70e18a5";

    interfaces.enp1s0 = {
      ipv4.addresses = [{ address = "10.100.0.206"; prefixLength = 23; }];
    };
    interfaces.enp2s0 = {
      ipv4.addresses = [{ address = "92.118.28.8"; prefixLength = 24; }];
      ipv6.addresses = [{ address = "2a09:a441::8"; prefixLength = 32; }];
    };
    defaultGateway = { address = "92.118.28.1"; interface = "enp2s0"; };
    defaultGateway6 = { address = "2a09:a441::1"; interface = "enp2s0"; };
  };
  my.ip.tailscale = "100.81.27.52";

  services.postgresql = {
    enable = true;
    ensureDatabases = [
      "netbox"
    ];
    ensureUsers = [{
      name = "netbox";
      ensurePermissions = { "DATABASE netbox" = "ALL PRIVILEGES"; };
    }];
  };
  services.postgresqlBackup.enable = true;

  services.redis.servers."" = {
    enable = true;
  };

  users.groups.netbox = {};
  users.users.netbox = {
    home = "/srv/netbox";
    isSystemUser = true;
    createHome = true;
    group = "netbox";
  };

  environment.systemPackages = with pkgs; [
    netbox
  ];

  systemd.services.netbox-rq = {
    wantedBy = [ "multi-user.target" ];
    after = [ "network-online.target" ];
    serviceConfig = {
      Type = "simple";
      User = "netbox";
      Group = "netbox";
      WorkingDirectory = "/srv/netbox";
      ExecStart = "${netbox}/bin/netbox-manage rqworker high default low";
      Restart = "on-failure";
      RestartSec = 30;
      PrivateTmp = true;
    };
  };

  systemd.services.netbox = {
    wantedBy = [ "multi-user.target" ];
    after = [ "network-online.target" ];
    serviceConfig = {
      Type = "simple";
      User = "netbox";
      Group = "netbox";
      WorkingDirectory = "/srv/netbox";
      PIDFile = "/srv/netbox/gunicorn.pid";
      ExecStart = "${netbox}/bin/netbox-gunicorn --pid /srv/netbox/gunicorn.pid --config ${netbox}/share/netbox/contrib/gunicorn.py netbox.wsgi";
      Restart = "on-failure";
      RestartSec = 30;
      PrivateTmp = true;
    };
  };

  services.nginx = {
    enable = true;
    recommendedProxySettings = true;
    virtualHosts."netbox.int.lukegb.com" = {
      locations."/static/" = {
        alias = "${netbox}/share/netbox/netbox/static/";
      };
      locations."/" = {
        proxyPass = "http://127.0.0.1:8001";
      };
    };
  };

  system.stateVersion = "21.05";
}