{ pkgs ? import <nixpkgs> { }, ffdd-server ? pkgs.fetchgit {
  url = "https://github.com/Freifunk-Dresden/ffdd-server.git";
  rev = "T_RELEASE_v1.3.0rc2";
  sha256 = "15iijpywfp0zd785na5ry0g8z41x3zg238piih5rp8khc5xis09c";
}, ddmeshNode, ... }:

with pkgs;
let
  nvram = {
    ddmesh_node = toString ddmeshNode;
    city = "Dresden";
    autoupdate = "0";
    contact_name = "C3D2";
    contact_location = "Zentralwerk";
    contact_email = "astro@spaceboyz.net";
    contact_note = "http://www.c3d2.ffdd/";
    gps_latitude = "51.0810624";
    gps_longitude = "13.7285866";
    gps_altitude = "100";
  };
in stdenv.mkDerivation {
  name = "sysinfo-json";
  src = "${ffdd-server}/salt/freifunk/base/ddmesh/";
  buildPhase = ''
    cat > bmxddump.sh <<EOF
    #!${bash}/bin/bash

    DB_PATH=/var/lib/freifunk/bmxd
    mkdir -p \$DB_PATH
    ${bmxd}/sbin/bmxd -c --gateways > \$DB_PATH/gateways
    ${bmxd}/sbin/bmxd -c --links > \$DB_PATH/links
    ${bmxd}/sbin/bmxd -c --originators > \$DB_PATH/originators
    ${bmxd}/sbin/bmxd -c --status > \$DB_PATH/status
    #${bmxd}/sbin/bmxd -c --networks > \$DB_PATH/networks
    ${bmxd}/sbin/bmxd -ci > \$DB_PATH/info
    EOF

    cat > lsb_release <<EOF
    #!${bash}/bin/bash

    ${lsb-release}/bin/lsb_release \$@ | \
      ${gnused}/bin/sed -e 's/"//g'
    EOF

    substitute usr/local/bin/ddmesh-ipcalc.sh ddmesh-ipcalc.sh \
      --replace awk ${gawk}/bin/awk
    substitute var/www_freifunk/sysinfo-json.cgi sysinfo-json.cgi \
      --replace "echo 'Content-Type: application/json;charset=UTF-8'" "" \
      --replace '"node_type":"server"' '"node_type":"node"' \
      --replace ddmesh-ipcalc.sh $out/bin/ddmesh-ipcalc.sh \
      --replace lsb_release $out/bin/lsb_release \
      --replace ${
        lib.strings.escapeShellArg
        "$(sudo /sbin/iptables -w -xvn -L stat_from_ovpn | awk '/RETURN/{print $2}')"
      } 0 \
      --replace ${
        lib.strings.escapeShellArg
        "$(sudo /sbin/iptables -w -xvn -L stat_to_ovpn | awk '/RETURN/{print $2}')"
      } 0 \
      --replace 'nettype_lookup[$2]' '"lan"' \
      --replace awk ${gawk}/bin/awk
  '' + lib.strings.concatStrings (lib.attrsets.mapAttrsToList (var: value: ''
    substituteInPlace sysinfo-json.cgi --replace ${
      lib.strings.escapeShellArg "$(uci -qX get ffdd.sys.${var})"
    } '${value}'
  '') nvram);
  installPhase = ''
    pwd
    mkdir -p $out/bin
    ls -la
    install -m 0755 sysinfo-json.cgi $out/bin/
    install -m 0755 ddmesh-ipcalc.sh $out/bin/
    install -m 0755 bmxddump.sh $out/bin/
    install -m 0755 lsb_release $out/bin/
  '';
}
