. $domainbasedir/config/config
. $apachebasedir/config/config

. $(dirname $BASH_SOURCE)/config

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

function domain_type()
{
  mne_need_error
  systemctl is-enabled samba-ad-dc.service 2>/dev/null >/dev/null
  if [ "$?" = "0" ]; then echo "primary"; else echo "standalone"; fi
}

# share
function get_groupnames()
{
    echo 'groupname="Mneshare $(Tolower $(hostname)) $(Tolower '$1')"'
    echo 'groupnameread="$groupname Read"'
}

# location
function check_path()
{
  local path=$(realpath "$datadir/$1")
  local length=${#datadir}
  local checkpath=${path:0:$length}
    
  if [ "$datadir" != "$checkpath" ]; then
    echo "$path : $datadir $length" >&$logfile
    echo "#mne_lang#Ordner ist nicht korrekt#" >&2
    exit 1
  fi
}

function read_shares()
{
    echo "declare -A shares;"
    prog='BEGIN        { share=""; description=""}
           /\[.*\]/    { if ( share != "" ) { printf("shares[\"%s\"]=\"%s\";", share, description); }
                         sub(/^.*\[/, "")
                         sub(/\].*$/, "")
                         share = $0
                         description = ""
                        }
          /comment/   { description = gensub(/^.*=[ \t]*/, "", 1 ); }
          END         { if ( share != "" ) { printf("shares[\"%s\"]=\"%s\";", share, description); } }
         '
    awk "$prog" < "$domainrootdir/shares.conf"
    
}

# share
function read_share()
{
echo $datadir >&$logfile
    local prog='/\[.*\]/   { start = 0 }
                /\['$1'\]/ { start = 1 ; printf ( "share=\"'$1'\";") }
               /read only/ { if ( start ) printf ("readonly=\"%s\";", ( $NF != "no" ) ? "true" : "false" ) }
               /path/      { path = gensub(/^.*=[ \t]*/, "", 1 ); sub(/'${datadir//\//\\/}'/, "", path ); if ( start) printf ("location=\"%s\";", path) }
               /comment/   { description = gensub(/^.*=[ \t]*/, "", 1 ); if ( start) printf ("description=\"%s\";", description) }
         '
    awk "$prog" < "$domainrootdir/shares.conf"
    
}

# dirname typ
function read_dir()
{
    echo 'declare -a files;'
    echo 'declare -A accesstime;'
    echo 'declare -A changetime;'
    echo 'declare -A filetype;'
    echo 'declare -A filesize;'
    
   find -L $datadir/$1 $2 ! -path "*/.trash" -mindepth 1 -maxdepth 1 -printf 'files[${#files[@]}]="%f";accesstime["%f"]="%As";changetime["%f"]="%Cs";filetype["%f"]="%y";filesize["%f"]="%s"\n'
}

# groupname prefix rw domaindn
function read_users()
{
    echo "declare -A $2firstname;"
    echo "declare -A $2lastname;"
    echo "declare -A $2login;"
    echo "declare -A $2fullname;"

    prog='/# record/ { start=1; uid=""; gid=""; login=""; firstname=""; lastname=""; fullname=""; i="" }
          /^$/       { if ( start != 1 ) next;
                       start=0;
                       if ( login == "" ) next;

                       if ( firstname == "" && lastname == "" ) firstname = login;
                       fullname=firstname
                       if ( lastname ) fullname = fullname " " lastname
                       i = fullname "-" login
                       printf("'$2'login[\"%s\"]=\"%s\";'$2'fullname[\"%s\"]=\"%s\";'$2'firstname[\"%s\"]=\"%s\";'$2'lastname[\"%s\"]=\"%s\"; rw[\"%s\"]='$3'\n", i, login, i, fullname, i, firstname, i, lastname, i );
                     }
      /^sAMAccountName:/     { login = gensub(/^.*: */, "", 1); }
      /^sn:/                 { lastname = gensub(/^.*: */, "", 1); }
      /^givenName:/          { firstname = gensub(/^.*: */, "", 1); }
      '

      ldbsearch -H /var/lib/samba/private/sam.ldb "(&(!(UserAccountControl:1.2.840.113556.1.4.803:=2))(objectClass=user)(!(objectClass=computer))(memberOf=CN=$1,CN=Users,$4))" | awk "$prog" >&$logfile
      ldbsearch -H /var/lib/samba/private/sam.ldb "(&(!(UserAccountControl:1.2.840.113556.1.4.803:=2))(objectClass=user)(!(objectClass=computer))(memberOf=CN=$1,CN=Users,$4))" | awk "$prog"

}

#domaintype share_old share location description readonly validuser rduser
function write_samba()
{
    local template="$(findtemplate share samba_$1.conf)"
    local rdonly="no"
    if [ "$6" = "1" ]; then rdonly="yes"; fi
    

    local prog='/####RELEASENAME####/ { gsub(/####RELEASENAME####/,"'$3'"); }
                /####FOLDERNAME####/  { gsub(/####FOLDERNAME####/,"'$datadir$4'");  }
                /####DESCRIPTION####/ { gsub(/####DESCRIPTION####/,"'$5'"); }
                /####READONLY####/    { gsub(/####READONLY####/,"'$rdonly'");    }
                /####VALIDUSER####/   { gsub(/####VALIDUSER####/,"'$7'");   }
                /####RDUSER####/      { gsub(/####RDUSER####/,"'$8'");      }
                                      { print $0 }'
    
    local share="$(awk "$prog" < $template )"
    
    prog='/\[.*\]/ { if ( found == 1 ) found = 0 } /\['$2'\]/ { found = 1;} { if ( found != 1 ) print $0 }'
    savefile "$domainrootdir/shares.conf"
    awk "$prog" < $savedfile > "$domainrootdir/shares.conf"
    
    if [ "$3" != "" ]; then
      echo "$share" >>  "$domainrootdir/shares.conf"
    fi
}

#domaintype domain domaindn bindpassword share_old share location description readonly
function write_apache()
{
    if [ "$domaintype" != "primary" ]; then
      echo "#mne_lang#Webdav Shares nur mit Domain möglich" >&2
      return;
    fi
    
    local err
    local template="$(findtemplate share webdav.conf)"
    local oldname="mne_webdav_$5.conf"
    local confname="mne_webdav_$6.conf"
    
    local groupname="Mneshare $(Tolower $hostname) $(Tolower $6)"
    local groupnameread="$groupname Read"
    
    rm -f "$apacherootdir/conf-available/$oldname" >&$logfile
    rm -f "$apacherootdir/conf-enabled/$oldname" >&$logfile

    if [ "$9" = "1" ]; then groupname="$groupname Disabled"; fi

    if [ "$6" != "" ]; then
      write_access "$7" "$groupname" "$groupnameread"
    
      local prog='/####RELEASENAME####/   { gsub(/####RELEASENAME####/,"'$6'"); }
                  /####FOLDERNAME####/    { gsub(/####FOLDERNAME####/,"'$datadir$7'");   }
                  /####DESCRIPTION####/   { gsub(/####DESCRIPTION####/,"'$8'"); }
                  /####GROUPNAME####/     { gsub(/####GROUPNAME####/,"'$groupname'"); }
                  /####GROUPNAMEREAD####/ { gsub(/####GROUPNAMEREAD####/,"'$groupnameread'"); }
                  /####BINDPASSWD####/    { gsub(/####BINDPASSWD####/,"'$4'"); }
                  /####DCDOMAIN####/      { gsub(/####DCDOMAIN####/,"'$3'"); }
                  /####HOSTNAME####/      { gsub(/####HOSTNAME####/,"'$(hostname)'"); }
                                          { print $0 }'
   
      awk "$prog" < "$template" > "$apacherootdir/conf-available/$confname"
      a2enconf "$confname" >&$logfile 2>&$logfile
    fi
    
    mne_need_error
    err="$(apachectl configtest 2>/dev/null >/dev/null ; exit $? )"
    if [ "$?" != "0" ]; then
       echo "$err" >$2
       a2disconf "$confname"
       exit 1
    fi
    
    systemctl reload apache2.service
}

# location groupname groupnamewrite
function write_access()
{
    local location=$1
    local groupname=$2
    local groupnameread=$3
    
    local path=$(realpath "$datadir$location")
    local length=${#datadir}
    local checkpath=${path:0:$length}
    
    if [ "$checkpath" != "$datadir" ] || [ ! -d "$path" ]; then
        echo "#mne_lang#Ordner ist nicht korrekt#" >&2
        exit 1
    fi

    mne_need_error 2
    samba-tool group list | egrep "^$groupname\$" 2>/dev/null >/dev/null
    if [ ! "$?" = "0" ]; then
      samba-tool group add "$groupname" >&$logfile 2>&$logfile
    fi

    mne_need_error 2
    samba-tool group list | egrep "^$groupnameread\$" 2>/dev/null >/dev/null
    if [ ! "$?" = "0" ]; then
       samba-tool group add "$groupnameread" >&$logfile 2>&$logfile
    fi
    
    dusid=$(wbinfo --name-to-sid="Domain Users" | cut -f1 "-d ")
    du="(A;OICI;0x001200a9;;;$dusid)"
    
    sddl=$(samba-tool ntacl get --as-sddl "$datadir" | sed -e "s/(A.*$//" )
    samba-tool ntacl set "$sddl$du" "$datadir"
    p=
    for dir in $(echo $location | tr "/" "\n")
    do
        sddl=$(samba-tool ntacl get --as-sddl "$datadir/$p/$dir" | sed -e "s/(A.*$//" )
        samba-tool ntacl set "$sddl$du" "$datadir/$p/$dir"
        p="$p/$dir"
    done
    
    wwsid=$(wbinfo --name-to-sid="www-data" | cut -f1 "-d ")
    wrsid=$(wbinfo --name-to-sid="$groupname" | cut -f1 "-d ")
    rdsid=$(wbinfo --name-to-sid="$groupnameread" | cut -f1 "-d ")

    ww="(A;OICI;0x001f01ff;;;$wwsid)"
    wr="(A;OICI;0x001f01ff;;;$wrsid)"
    rd="(A;OICI;0x001200a9;;;$rdsid)"

    sddl=$(samba-tool ntacl get --as-sddl "$path" | sed -e "s/(A.*$//" )
    samba-tool ntacl set "$sddl$wr$rd$ww" "$path"

    chmod g+s "$path"
    ( cd "$path"; getfacl . | setfacl -R --set-file=- . )
    
    smbcontrol all reload-config
}
