. $(dirname $BASH_SOURCE)/config

#if [ ! -d "$apacheconfigdir" ]; then
#	mkdir -p "$apacheconfigdir";
#fi


# domain
function check_dnspasswd()
{
  local hostname=$(hostname)
  mne_need_error
  kinit -F -k -t /var/lib/samba/dhcpd-dns/dhcpd.keytab dns-$hostname@$(echo ${1^^}) >/dev/null 2>&$logfile 
  if [ "$?" != "0" ]; then
    kinit -F -k -t /var/lib/samba/dhcpd-dns/dhcpd.keytab dns-${hostname^^}@$(echo ${1^^})
  fi
}

function check_cert()
{
  if [ ! -f  $certcadir/ca.crt ] || [ ! -f $certcertdir/$(hostname).crt ]; then
    echo 'need certificates for provisoring domain' 1>&2;
    exit 1
  fi

  chown root:root $certkeydir/$(hostname).key 2>&$logfile

  chmod 600 $certkeydir/$(hostname).key 2>&$logfile
  chmod 644 $certcertdir/$(hostname).crt 2>&$logfile

  chmod 600 $certcadir/ca.key 2>&$logfile
  chmod 644 $certcadir/ca.crt 2>&$logfile

  mne_error_ignore=1
  rm /usr/local/share/ca-certificates/mne_sbsca_$(hostname).crt >&$logfile 2>&$logfile
  mne_error_ignore=
  ln -s $certcadir/ca.crt /usr/local/share/ca-certificates/mne_sbsca_$(hostname).crt
  update-ca-certificates >&$logfile 2>&$logfile
}

# workgroup globalextra
function mod_cert()
{
    local prog='/####CERTCERTDIR####/     { gsub(/####CERTCERTDIR####/,"'"$certcertdir"'"); }
                /####CERTKEYDIR####/      { gsub(/####CERTKEYDIR####/,"'"$certkeydir"'"); }
                /####CERTCADIR####/       { gsub(/####CERTCADIR####/,"'"$certcadir"'"); }
                /####HOST####/            { gsub(/####HOST####/,"'"$(hostname)"'"); }
                /####WORKGROUP####/       { gsub(/####WORKGROUP####/,"'"$1"'"); }
                                          { print $0 }'

    awk "$prog" < $2 > $domainrootdir/globalextra.conf
}

# device hostname domain
function check_host()
{
    local addr=$1
    local hostname=$2
    local domain=$3
    
    addr=$(ip addr show $1 | awk '/inet\b/ { if ( substr($2, 1, 4) != "fe80" ) { split($2, a, "/"); print a[1]} }' )
#    rm -f /tmp/hosts$$
#    for addr in $addrs
#    do
#        echo "$addr $2 $2.$3" >> /tmp/hosts$$
#    done

#    prog=' /'$hostname'/ { next; } { print $0 }'
#    awk "$prog" < /etc/hosts >> /tmp/hosts$$
#    mv /tmp/hosts$$ /etc/hosts
    
    echo $addr
}

function rm_config()
{
    rm -rf /var/run/samba/* >&$logfile 2>&$logfile
    rm -rf /var/lib/samba   >&$logfile 2>&$logfile

    mkdir -p /var/lib/samba >&$logfile 2>&$logfile

    mne_ignore_error=1
    if [ -f $domainrootdir/smb.conf ];then
        rm $domainrootdir/smb.conf >&$logfile 2>&$logfile
        rm $domainrootdir/validuser.conf >&$logfile 2>&$logfile
        rm $domainrootdir/shares.conf >&$logfile 2>&$logfile
        rm $domainrootdir/globalextra.conf >&$logfile 2>&$logfile
    fi
    mne_ignore_error=
}

function mod_smbconf()
{
    local prog="/\[global\]/ { start=1; print \$0; next;}
   /^[    ]*$|^\[/  { if ( start == 1 )
                    {
                      print \"        include = $domainrootdir/localextra.conf\";
                      print \"        include = $domainrootdir/globalextra.conf\";
                      print \"        include = $domainrootdir/dnsforward.conf\";
                      print \"        include = $domainrootdir/dhcp.conf\";
                      start = 2;
                     }
                   }
                   { print \$0; }
               END { print \"include = $domainrootdir/shares.conf\"; } "
    
    awk "$prog" < $domainrootdir/smb.conf  > /tmp/smb.$$
    mv /tmp/smb.$$ $domainrootdir/smb.conf;
    
    touch $domainrootdir/localextra.conf;
    touch $domainrootdir/globalextra.conf;
    touch $domainrootdir/dhcp.conf;
    touch $domainrootdir/dnsforward.conf;
    touch $domainrootdir/shares.conf;
}

# namedoption
function mod_bind()
{
  fgrep "$domainbindroot/named.conf.samba" $domainbindroot/named.conf 1>&$logfile 2>&$logfile
  if [ "$?" != "0" ];then
    savefile $domainbindroot/named.conf
    echo "include \"$domainbindroot/named.conf.samba\";" >> $domainbindroot/named.conf
  fi
  
  cat << EOF >"$domainbindroot/named.conf.samba"
dlz "AD DNS Zone" {
    database "dlopen /usr/lib/$(uname -i)-linux-gnu/samba/bind9/dlz_bind9_18.so";
};
EOF
  
  touch $domainbindroot/named.conf.options.local
  touch $domainbindroot/named.conf.options.forwarders
  
  savefile $domainbindroot/named.conf.options
  cp "$1" $domainbindroot/named.conf.options

  chmod 640 /var/lib/samba/private/dns.keytab
  chown root:bind /var/lib/samba/private/dns.keytab
  chown root:bind $domainbindroot/rndc.key
}

function get_reverse()
{
  local record=$1
  local search=$2

  echo "zone=\"\";raddr=\"\";"

  samba-tool dns zonelist $(hostname) --reverse --use-kerberos=required | awk '/pszZoneName/ { if ( substr($3,1,1) != "_" && substr($3,1,1) != ".") print $3 }' | \
  while read zone
  do
    if [ "$(echo $zone | awk '/ip6.arpa/ { print "AAAA" } /in-addr.arpa/ { print "A" }')" == "$record" ]; then
      if [ "$record" = "A" ]; then
        addr=$(echo $zone | sed -e 's/\.in-addr.arpa.*//' | tr "." $'\n' | tac | awk '{ print $0; count++} END { mask=count *8; while ( count++ < 4 ) print "0"; print "/" mask }' | paste -s -d "." | sed -e "s@\./@/@")
        if [ "$(netmask $search/${addr#*/} | sed -e 's/^[[:space:]]*//')" == "$addr" ]; then
          let num="4-${addr#*/}/8"
          echo "zone=\"$zone\";raddr=\"$(echo $search | tr -d "[:blank:]" | cut -d/ -f1 | tr "." $'\n' | tail -$num | tac | paste -s -d '.')\""
          return
        fi
      else
        addr=$(ipv6calc -I revnibbles.arpa $zone)
        if [ "$(netmask $search/${addr#*/} | sed -e 's/^[[:space:]]*//')" == "$addr" ]; then
          let num="${addr#*/}/4"
          echo zone="\"$zone\";raddr=\"$(ipv6calc -a -I ipv6addr $search | tr "." $'\n' | head -n $num | paste -s -d '.')\""
          return
        fi
      fi
    fi
  done
}

# domain netdevice dnsforward dnssearch
function mod_netpar()
{
    local template=$(findtemplate domain hosts )
    savefile /etc/hosts
    cp "$template" /etc/hosts
    
    sed -e '/^passwd:/s@ *winbind@@' -e '/^passwd:/s@$@ winbind@' -e '/^group:/s@ *winbind@@' -e '/^group:/s@$@ winbind@' < /etc/nsswitch.conf  > /tmp/nsswitch.$$
    mv /tmp/nsswitch.$$ /etc/nsswitch.conf
    
    sed -e "/interfaces =/s@interfaces.*\$@interfaces = lo $2@" < $domainrootdir/smb.conf  > /tmp/smb.$$; 
    mv /tmp/smb.$$ $domainrootdir/smb.conf;
    
    sed -e "/TLS_REQCERT/d" < /etc/ldap/ldap.conf  > /tmp/ldap.$$; 
    mv /tmp/ldap.$$ /etc/ldap/ldap.conf;
    echo "" >> $ldapconf/ldap.conf
    echo "TLS_REQCERT allow" >> /etc/ldap/ldap.conf
    
    if [ "$3" != "" ]; then
        echo "$3" | sed -e 's/$/;\n};/g ;'\
                                 -e 's/,/ /g'\
                                 -e 's/  */;\n    /g'\
                                 -e 's/^/    /'\
                                 -e '1 i forwarders {' > $domainbindroot/named.conf.options.forwarders;
    else
        echo "" > $bindconf/named.conf.options.forwarders;
    fi
    
    rm -f /etc/resolv.conf 1>&$logfile 2>&$logfile
    echo "nameserver 127.0.0.1"  > /etc/resolv.conf
    echo "domain $1" >> /etc/resolv.conf
    if [ "$4" != "" ]; then
       echo "search $1 $4" | awk -v RS=' '  '{ if (!seen[$1]++) { printf "%s%s",sep,$1; sep=" " } }' >> /etc/resolv.conf
    fi
    
    systemctl restart named >&$logfile 2>&$logfile
}


function mod_kerberos()
{
    savefile "$domainkerberosfile"
    cp /var/lib/samba/private/krb5.conf $domainkerberosfile
    echo ""                       >>  $domainkerberosfile
    echo "[realms]"               >>  $domainkerberosfile
    echo "  $udomain = {"         >>  $domainkerberosfile
    echo "    kdc = localhost:88" >>  $domainkerberosfile
    echo "  }"                    >>  $domainkerberosfile
}

# ip4dnsaddr ip4start ip4end ip6dnsaddr ip6start ip6end
# domain dnssearch broadcast router dummy
# dhcpconf4 $dhcpconf6 dhcpupdate radvdconf
function mod_dhcp()
{
    mkdir -p /etc/mne/dhcpd 1>&$logfile 2>&$logfile
    touch /etc/dhcp/fix.conf 1>&$logfile 2>&$logfile
    touch /etc/dhcp/fix6.conf 1>&$logfile 2>&$logfile
    
    dhcp_mod_appamor
    
    mkdir -p /var/lib/samba/dhcpd-dns >&$logfile 2>&$logfile
    chown root:dhcpd /var/lib/samba/dhcpd-dns >&$logfile 2>&$logfile
    chmod 750 /var/lib/samba/dhcpd-dns >&$logfile 2>&$logfile
    cp /var/lib/samba/bind-dns/dns.keytab /var/lib/samba/dhcpd-dns/dhcpd.keytab 
    chown root:dhcpd /var/lib/samba/dhcpd-dns/dhcpd.keytab 
    
    local ip4netdevice=
    local ip6netdevice=
    local ip4addr="$1"
    local ip6addr="$4"
    
    systemctl stop  isc-dhcp-server  2>&$logfile 1>&$logfile
    systemctl stop  isc-dhcp-server6 2>&$logfile 1>&$logfile
    systemctl stop  radvd            2>&$logfile 1>&$logfile
    
    systemctl disable  isc-dhcp-server  2>&$logfile 1>&$logfile
    systemctl disable  isc-dhcp-server6 2>&$logfile 1>&$logfile
    systemctl disable radvd             2>&$logfile 1>&$logfile

    net=0.0.0.0/32
    if [ "$2" != "" ] && [ "$3" != "" ]; then
      for netdevice in $(ls /sys/class/net)
      do
        for addr in $(ip -4 address show dev $netdevice | awk '/inet/ { print $2 }')
        do
            mask=$(echo $addr | cut -f2 -d/)
            net=$(netmask $addr)

            netstart=$(netmask $2/$mask)
            netend=$(netmask $3/$mask)
          
            if [ "$netstart" != "$net" ]; then continue; fi;
            if [ "$netend" != "$net" ]; then continue; fi;
        
            if [ "$ip4addr" = "" ]; then
              ip4addr="$addr"
            fi
          
            ip4netdevice=$netdevice
            ip4broadcast=$(sipcalc -4 $addr | awk '/Broadcast/ { print $4 }')
            ip4router=$(route -n  | awk '/^0\.0\.0\.0.*'$device'/ { print $2 }')
          
            systemctl enable  isc-dhcp-server 2>&$logfile 1>&$logfile
            break;
        done
        if [ "$ip4netdevice" != "" ]; then break; fi;
      done
      
      if [ "$ip4netdevice" == "" ]; then
        echo "#mne_lang#falsches Netzwerk der DHCP IPv4 Adresse#" >&2;
        exit 1;
      fi
    fi
    
    net6=0000::/64
    if [ "$5" != "" ] && [ "$6" != "" ]; then
      for netdevice in $(ls /sys/class/net)
      do
        for addr in $(ip -6 address show dev $netdevice | awk '/inet6/ { if ( substr($2,1,4) != "fe80" ) print $2 } ')
        do
          mask6=$(echo $addr | cut -f2 -d/)
          net6=$(ipv6calc --addr2compaddr $(sipcalc $addr | fgrep -i subnet | cut -d '-' -f 2))
  
          if [ "$5" != "" ]; then
              net6start=$(ipv6calc --addr2compaddr $(sipcalc $5/$mask6 | fgrep -i subnet | cut -d '-' -f 2))
          fi

          if [ "$6" != "" ]; then
              net6end=$(ipv6calc --addr2compaddr $(sipcalc $6/$mask6 | fgrep -i subnet | cut -d '-' -f 2))
          fi

          if [ "$net6start" != "$net6" ]; then continue; fi;
          if [ "$net6end" != "$net6" ]; then continue; fi;
        
          ip6netdevice=$netdevice
        
          if [ "$ip6addr" = "" ];then
            ip6addr=$addr
          fi
        
          ip6router=$(route -6n | awk '/::\/0.*'$netdevice'/ { print $2 }')
          systemctl enable  isc-dhcp-server6 2>&$logfile 1>&$logfile
          systemctl enable radvd             2>&$logfile 1>&$logfile
        
          break;
        done
        
        if [ "$ip6netdevice" != "" ]; then break; fi;
      done
      
      if [ "$ip6netdevice" == "" ]; then
        echo "#mne_lang#falsches Netzwerk der DHCP IPv6 Adresse#" >&2;
        exit 1;
      fi
    fi
    
    prog='/####DOMAIN####/     { gsub(/####DOMAIN####/,"'$7'"); }
      /####HOST####/       { gsub(/####HOST####/,"'$(hostname)'"); }
      /####DSEARCH####/    { gsub(/####DSEARCH####/,"'$(echo "$7 $8" | awk -v RS=' '  '{ if (!seen[$1]++) { printf "%s%s",sep,$1; sep=" " } }' | sed -e 's/^ */\\"/' -e 's/ *$/\\"/' -e 's/  */\\", \\"/g')'"); }
      /####DNSADDR####/    { gsub(/####DNSADDR####/,"'$( echo $ip4addr | cut -f1 -d/)'"); }
      /####DNSADDR6####/   { gsub(/####DNSADDR6####/,"'$( echo $ip6addr | cut -f1 -d/)'"); }
      /####MASK####/       { gsub(/####MASK####/,"'$(ipnetmask mask)'"); }
      /####NET####/        { gsub(/####NET####/,"'$( echo $net | cut -f1 -d/)'"); }
      /####NET6####/       { gsub(/####NET6####/,"'$net6'"); }
      /####START####/      { gsub(/####START####/,"'$2'"); }
      /####END####/        { gsub(/####END####/,"'$3'"); }
      /####START6####/     { gsub(/####START6####/,"'$5'"); }
      /####END6####/       { gsub(/####END6####/,"'$6'"); }
      /####BCAST####/      { gsub(/####BCAST####/,"'$ip4broadcast'"); }
      /####ROUTER4####/     { gsub(/####ROUTER4####/,"'$ip4router'"); }
      /####ROUTER6####/     { gsub(/####ROUTER6####/,"'$ip6router'"); }
      /####NETDEVICE####/  { gsub(/####NETDEVICE####/,"'$ip6netdevice'"); }
                           { print $0 }'
    
    savefile /etc/dhcp/dhcpd.conf
    savefile /etc/dhcp/dhcpd6.conf
    savefile /etc/radvd.conf
    savefile /etc/mne/dhcpd/update-samba-dns.sh
    savefile /etc/default/isc-dhcp-server

    awk "$prog" < ${12} > /etc/dhcp/dhcpd.conf
    awk "$prog" < ${13} > /etc/dhcp/dhcpd6.conf
    awk "$prog" < ${14} > /etc/mne/dhcpd/update-samba-dns.sh
    awk "$prog" < ${15} > /etc/radvd.conf
    
    chmod +x /etc/mne/dhcpd/update-samba-dns.sh
    
    echo "INTERFACESv4=\"$ip4netdevice\""  > /etc/default/isc-dhcp-server
    echo "INTERFACESv6=\"$ip6netdevice\"" >> /etc/default/isc-dhcp-server
    
    if [ "$ip4netdevice" ]; then systemctl start isc-dhcp-server; fi
    if [ "$ip6netdevice" ]; then systemctl start isc-dhcp-server6; systemctl start radvd; fi
}

function dhcp_mod_appamor()
{
    if [ -f $apparmorconf/usr.sbin.dhcpd ]; then
      sed -e "s/^.*include <dhcpd.d>/  include <dhcpd.d>/" < $apparmorconf/usr.sbin.dhcpd > /tmp/dhcpd.$$
      mv /tmp/dhcpd.$$ /etc/apparmor.d/usr.sbin.dhcpd
    fi
    
    mkdir -p /etc/apparmor.d/dhcpd.d
    echo "       /etc/mne/dhcpd/update-samba-dns.sh Ux," > /etc/apparmor.d/dhcpd.d/samba_dhcpd
    
}

# hostold host addr mac fix comment addrtyp
function dhcp_fix_mod()
{

  if [ "$7" = "A" ]; then
    addrtyp=
    idname="hardware ethernet"
    mask=$(ipmask2int $(awk '/subnet.*{/ { print $4 }' < /etc/dhcp/dhcpd.conf ))
    if [ "$(awk '/subnet.*{/ { print $2 "/'$mask'"}' < /etc/dhcp/dhcpd.conf)" != "$(netmask $3/$mask | sed -e 's/^[[:space:]]*//')" ]; then
      return 0
    fi
  elif [ "$7" = "AAAA" ]; then
    addrtyp=6
    idname="host-identifier option dhcp6.client-id"
    net="$(awk '/subnet6.*{/ { print $2 }' < /etc/dhcp/dhcpd6.conf)"
    if [ "$net" != "$(netmask $3/${net#*/} | sed -e 's/^[[:space:]]*//')" ]; then
      return 0
    fi
  else
    return 0;
  fi
  
  prog='/host[ \t]+'$1'[ \t]*{/ { hostfound=1; }
        /}/                     { if ( hostfound ) { hostfound=0; next; }}
        /#}/                    { if ( hostfound ) { hostfound=0; next; }}
                                { if ( hostfound != 1 ) print $0 }
                  END           { 
                                   if ( "'$2'" != "" && "'$3'" != "" )
                                   {
                                     kommentar = ( '"$5"' == 1 ) ? " " : "#";
                                     printf("%s   host '"$2"' {\n", kommentar );
                                     printf("#mnecomment'$6'\n" );
                                     printf("%s              option host-name \"'"$2"'\";\n", kommentar );
                                     printf("%s              ddns-hostname \"'"$2"'\";\n", kommentar );
                                     printf("%s              '"$idname"' '"$4"';\n", kommentar );
                                     printf("%s              fixed-address'$addrtyp' '"$3"';\n", kommentar );
                                     printf("%s   }\n", kommentar);
                                   }
                                }'
   
   awk "$prog" < "/etc/dhcp/fix$addrtyp.conf" > /tmp/fix$$
   mv /tmp/fix$$ "/etc/dhcp/fix$addrtyp.conf"
   chown dhcpd:dhcpd "/etc/dhcp/fix$addrtyp.conf"

}
# host addrtyp
function dhcp_fix_del()
{

  if [ "$2" = "A" ]; then
    filename=/etc/dhcp/fix.conf
  else
    filename=/etc/dhcp/fix6.conf
  fi

  prog='/host[ \t]+'$1'[ \t]*{/ { hostfound=1; host = ( substr($0,1,1) == "#" ) ? $3 : $2; }
        /}/                        { if ( hostfound )
                                     {
                                       hostfound=0;
                                       next;
                                     }
                                   }
                                   { if ( hostfound != 1 ) print $0 }'
   
   awk "$prog" < $filename > /tmp/fix$$
   mv /tmp/fix$$ $filename
   chown dhcpd:dhcpd "$filename"

}


