#!/bin/sh

if [ ! $(whoami) = "root" ]; then
 echo "You need to be root to run this command."
 exit 1
fi

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin; export PATH

RUNNING_FREEBSD_VERSION=$(uname -r | awk -F '-' '{print $1}')
RUNNING_FREEBSD_ARCH=$(uname -m)

case ${RUNNING_FREEBSD_VERSION} in
  "9.2"|"9.3"|"10.0"|"10.1"|"10.2") ;;
  *)
    echo "Unsupported FreeBSD version \"${RUNNING_FREEBSD_VERSION}\"."
    echo "Supported versions are \"9.2\", \"9.3\", \"10.0\", \"10.1\" or \"10.2\". Exiting."
    exit 1
  ;;
esac

run_command() {

  #############################################################################
  ## This function exists for two reasons; 1) to give better feedback to the ##
  ## user and 2) provide a rudimentary form of error checking to just bail   ##
  ## out if things go south.                                                 ##
  ##                                                                         ##
  ## Two important things to know about it.                                  ##
  ## - Always remember to begin and end the command you want to have run     ##
  ## with quotation marks to have it passed through as just one long string. ##
  ## - Any quotation marks inside the command have to be commented out by    ##
  ## prefixing with a backslash so that they pass through "echo" as literal  ##
  ## quotes. Example:                                                        ##
  ## run_command "echo \"\""                                                 ##
  ## To pass through those same characters but literally(\"):                ##
  ## run_command "echo \\\"\\\""                                             ##
  #############################################################################

  RUN_DIR="/var/tmp"
  if [ ! -d ${RUN_DIR} ]; then
    mkdir ${RUN_DIR}
    chown root:$(id root | awk '{gsub(/\(/, " "); gsub(/\)/, " "); if ($3 ~ "gid") print $4}') ${RUN_DIR}
    chmod 777 ${RUN_DIR}
  fi
  COMMAND=$(mktemp ${RUN_DIR}/run_command.cmd.XXXXXX)
  OUTPUT=$(mktemp ${RUN_DIR}/run_command.out.XXXXXX)
  echo "#!/bin/sh" > ${COMMAND}
  echo "$1" >> ${COMMAND}
  chmod +x ${COMMAND}
  echo "+-- Running command:"
  echo "$(cat ${COMMAND} | egrep -v "^#!/bin/sh$")"
  ${COMMAND} > ${OUTPUT} 2>&1
  if [ $? -gt "0" ]; then
    echo "+-- Command Failed!"
    echo "+-- Output was:"
    echo "$(cat ${OUTPUT})"
    echo ""
    rm ${OUTPUT} > /dev/null 2>&1
    rm ${COMMAND} > /dev/null 2>&1
    exit 1
  else
    echo "+-- Command succeeded."
    echo ""
  fi
  rm ${OUTPUT} > /dev/null 2>&1
  rm ${COMMAND} > /dev/null 2>&1
}

while [ $(ping -c 1 130.238.96.1 2>/dev/null | grep "bytes from" | awk 'END{print NR}') = "0" ]; do
 echo "+-- No response from primary DNS, sleeping."
 sleep 1
done

IFACE=$(for i in $(ifconfig | awk '/^[a-zA-Z]+[0-9]+/ {gsub(/\:/, ""); print $1}'); do if ifconfig $i | grep -q $(netstat -rn | awk '/default/ {gsub(/\./, " "); print $2"."$3"."$4}'); then echo $i; fi; done)
IPADDR=$(ifconfig ${IFACE} | awk '($1 == "inet") {sub(/\:/, ""); print $2}')
NETMASK=$(netstat -rn | grep $(echo ${IPADDR} | awk -F '.' '{print $1"."$2"."$3".0"}') | awk '{sub(/\//, " "); print $2}')
FULL_COMPUTERNAME=$(host $(echo ${IPADDR}) | awk '{print $5}' | awk -F '.' '{print $1}')
DOMAIN_NAME=$(host $(echo ${IPADDR}) | awk '{print $5}' | awk '{sub(/\.$/,"");printf("%s\n",substr($1,index($1,".")+1))}')
HOST_NAME=${FULL_COMPUTERNAME}.${DOMAIN_NAME}
if [ $(echo ${FULL_COMPUTERNAME} | awk -F "-" '{print $1"-"$2"-"$3"-"$4}') = "ovirt-0-1a-4a" ]; then
  SHORT_COMPUTERNAME=$(echo ${FULL_COMPUTERNAME} | awk -F "-" '{print $1"-"$5"-"$6"-"$7}')
  NETBIOS_COMPUTERNAME=$(echo ${SHORT_COMPUTERNAME} | awk '{print toupper ($1)}')
else
  NETBIOS_COMPUTERNAME=$(echo ${FULL_COMPUTERNAME} | awk '{print toupper ($1)}')
fi
for DISK in $(ls -1 /dev/ | egrep '(da|vtbd)' | egrep -v [a-z]+[0-9]+[a-z][0-9]+); do
  HDD=$(camcontrol devlist | egrep "\(${DISK},|,${DISK}\)" | egrep '(ATA|QEMU HARDDISK)' | awk 'END{print NR}')
  if [ ${HDD} = 1 ]; then
    HDDS="${HDDS} /dev/${DISK}"
  else
    DEVICE_NUMBER=$(echo ${DISK} | awk '{gsub(/[a-zA-Z]/, ""); print}')
    if [ $(grep "vtblk${DEVICE_NUMBER}" /var/run/dmesg.boot | awk 'END{print NR}') -gt "0" ]; then
      HDDS="${HDDS} /dev/${DISK}"
    fi
  fi
done
HDDS=$(echo ${HDDS} | sed 's/^ //')

if [ $(zfs list -o name | grep -c 'pool1/root') -ne 0 ]; then
  run_command "zfs set readonly=off pool1/root"
fi

if ! TMPDIR=/dev/null ASSUME_ALWAYS_YES=yes \
  PACKAGESITE=file:///nonexistent \
  pkg info -x 'pkg(-devel)?$' >/dev/null 2>&1; then

  PACKAGESITE=ftp://pkgmaster.slu.se/pub/FreeBSD/ports/amd64/packages-9-stable/Latest/; export PACKAGESITE
  run_command "pkg_add -r pkg"
  unset PACKAGESITE
fi

if ! grep -q 'WITH_PKGNG="YES"' /etc/make.conf 2>/dev/null; then
  run_command "echo 'WITH_PKGNG=\"YES\"' >>/etc/make.conf"
fi

if [ -f /var/db/pkg/pkgdb.db ]; then
  run_command "pkg2ng"
fi

if [ -f /etc/pkg/FreeBSD.conf ]; then
  if grep -q 'enabled: yes' /etc/pkg/FreeBSD.conf 2>/dev/null; then
    run_command "sed -i '' 's/enabled: yes/enabled: no/' /etc/pkg/FreeBSD.conf"
  fi
fi

if [ ! -d /usr/local/etc/ssl/certs ]; then
  run_command "mkdir -p /usr/local/etc/ssl/certs"
fi

if [ ! -f /usr/local/etc/ssl/certs/pkg.cert ]; then
  run_command "cat > /usr/local/etc/ssl/certs/pkg.cert << EOF
-----BEGIN PUBLIC KEY-----
[payload removed: 736 characters in 12 lines]
-----END PUBLIC KEY-----
EOF"
fi

if [ ! -f /usr/local/etc/pkg.conf ]; then
  run_command "cat > /usr/local/etc/pkg.conf << EOF
REPO_AUTOUPDATE     : YES
ALIAS               : {
  all-depends: query %dn-%dv,
  annotations: info -A,
  build-depends: info -qd,
  download: fetch,
  iinfo: info -i -g -x,
  isearch: search -i -g -x,
  leaf: query -e \"%a == 0\" \"%n-%v\",
  leaf: query -e \"%a == 0\" \"%n-%v\",
  list: info -ql,
  origin: info -qo,
  provided-depends: info -qb,
  raw: info -R,
  required-depends: info -qr,
  shared-depends: info -qB,
  show: info -f -k,
  size: info -sq,
  }
EOF"
fi

REPOS_DIR="/usr/local/etc/pkg/repos"

if [ ! -d ${REPOS_DIR} ]; then
  run_command "mkdir -p ${REPOS_DIR}"
fi

if [ ! -f ${REPOS_DIR}/pkgmaster.conf ]; then
  run_command "echo 'pkgmaster: {' > ${REPOS_DIR}/pkgmaster.conf"
  case "${RUNNING_FREEBSD_VERSION}" in
    "9.2")
      run_command "echo '    url             : \"http://pkgmaster.slu.se/repo/release92amd64-default\",' >> ${REPOS_DIR}/pkgmaster.conf"
    ;;
    "9.3")
      run_command "echo '    url             : \"http://pkgmaster.slu.se/repo/release93amd64-default\",' >> ${REPOS_DIR}/pkgmaster.conf"
    ;;
    "10.0")
      case "${RUNNING_FREEBSD_ARCH}" in
        "amd64")
          run_command "echo '    url             : \"http://pkgmaster.slu.se/repo/release10amd64-default\",' >> ${REPOS_DIR}/pkgmaster.conf"
        ;;
        "i386")
          run_command "echo '    url             : \"http://pkgmaster.slu.se/repo/release10i386-default\",' >> ${REPOS_DIR}/pkgmaster.conf"
        ;;
      esac
    ;;
    "10.1")
      run_command "echo '    url             : \"http://pkgmaster.slu.se/repo/release101amd64-default\",' >> ${REPOS_DIR}/pkgmaster.conf"
    ;;
    "10.2")
      run_command "echo '    url             : \"http://pkgmaster.slu.se/repo/release102amd64-default\",' >> ${REPOS_DIR}/pkgmaster.conf"
    ;;
  esac
  run_command "cat >> ${REPOS_DIR}/pkgmaster.conf << EOF
    signature_type  : \"PUBKEY\",
    pubkey          : \"/usr/local/etc/ssl/certs/pkg.cert\",
    enabled         : yes,
    mirror_type     : NONE,
}
EOF"
fi

if [ -f ${REPOS_DIR}/FreeBSD.conf ]; then
  if grep -q 'enabled: yes' ${REPOS_DIR}/FreeBSD.conf 2>/dev/null; then
    run_command "sed -i '' 's/enabled: yes/enabled: no/' ${REPOS_DIR}/FreeBSD.conf"
  fi
else
  run_command "echo 'FreeBSD: { enabled: no }' > ${REPOS_DIR}/FreeBSD.conf"
fi

run_command "pkg upgrade -fy pkg"
run_command "pkg update -f"

run_command "pkg install -y bash smartmontools samba36 pam_mkhomedir sudo zfsnap subversion ssmtp pkgconf openssl"
run_command "sed -i '' \"/# root:	me@my.domain/{G;s/$/root:	storageadm@slu.se/;}\" /etc/aliases"
run_command "newaliases"
run_command "cat > /usr/local/etc/ssmtp/ssmtp.conf << EOF
root=storageadm@slu.se
mailhub=smtp.slu.se:25
hostname=${HOST_NAME}
EOF"
run_command "cd /usr/ports/mail/ssmtp/; make replace"
run_command "sed -i '' \"s/Charlie &:\/root:\/bin\/csh/${FULL_COMPUTERNAME}@slu.se:\/root:\/bin\/csh/\" /etc/master.passwd"
run_command "pwd_mkdb -p /etc/master.passwd"
run_command "sed -i '' \"/#*.*						@loghost/{G;s/$/*.*						@syslog.slu.se/;}\" /etc/syslog.conf"
if service syslogd status | grep -q "is not running"; then
  run_command "service syslogd start"
else
  run_command "service syslogd restart"
fi
run_command "echo 'smartd_enable=\"YES\"' >> /etc/rc.conf"
run_command "cp /usr/local/etc/smartd.conf.sample /usr/local/etc/smartd.conf"
run_command "cat > /etc/periodic.conf << EOF
daily_status_zfs_enable=\"YES\"
daily_status_smart_devices=\"${HDDS}\"
EOF"
if service smartd status | grep -q "is not running"; then
  if ! ls -1 /dev/ | grep -q vtbd; then
    run_command "service smartd start"
  fi
else
  if ! ls -1 /dev/ | grep -q vtbd; then
    run_command "service smartd restart"
  fi
fi
run_command "cat > /etc/krb5.conf << EOF
 [logging]
    default = FILE:/var/log/krb5.log

[libdefaults]
    default_realm = AD.SLU.SE
    kdc_timesync = 1
    ccache_type = 4
    forwardable = true
    proxiable = true

[realms]
    AD.SLU.SE = {
        kdc = ad.slu.se
        admin_server = ad.slu.se
        default_domain = AD.SLU.SE
    }

[domain_realm]
    .ad.slu.se = AD.SLU.SE
    ad.slu.se = AD.SLU.SE
EOF"
run_command "cat > /usr/local/etc/smb.conf << EOF
 [global]

        server string = %h server (Samba, FreeBSD)
        security = ads
        realm = AD.SLU.SE
        workgroup = AD
        idmap config * : range = 16777216-33554431
        winbind use default domain = true
        winbind offline logon = true
        template homedir = /usr/home/%U
        template shell = /usr/local/bin/bash
        username map = /usr/local/etc/samba/usermap
        log level = 3
        log file = /var/log/samba/samba.log
        max log size = 50

        netbios name = ${NETBIOS_COMPUTERNAME}
        interfaces = ${IPADDR}/${NETMASK}
	nmbd bind explicit broadcast = no
EOF"
if [ ! -d /usr/local/etc/samba ]; then
  mkdir /usr/local/etc/samba
fi
run_command "cat > /usr/local/etc/samba/usermap << EOF
root=Administrator
guest=nobody
EOF"
run_command "sed -i '' -e 's/group: compat/group: files winbind/' -e 's/passwd: compat/passwd: files winbind/' /etc/nsswitch.conf"
run_command "cp /etc/pam.d/system /etc/pam.d/system.orig"
run_command "cat > /etc/pam.d/system << EOF
# auth
auth            sufficient      pam_opie.so                     no_warn no_fake_prompts
auth            requisite       pam_opieaccess.so               no_warn allow_local
auth            sufficient      pam_krb5.so                     no_warn try_first_pass
#auth           sufficient      pam_ssh.so                      no_warn try_first_pass
auth            sufficient      pam_unix.so                     no_warn try_first_pass nullok
auth            required        /usr/local/lib/pam_winbind.so   try_first_pass

# account
account         required        pam_krb5.so
account         required        pam_login_access.so
account         required        pam_unix.so

# session
#session        optional        pam_ssh.so
session         required        /usr/local/lib/pam_mkhomedir.so
session         required        pam_lastlog.so          no_fail

# password
password        sufficient      pam_krb5.so             no_warn try_first_pass
password        required        pam_unix.so             no_warn try_first_pass
EOF"
run_command "cp /etc/pam.d/system /etc/pam.d/system.ad"
run_command "cp /etc/pam.d/sshd /etc/pam.d/sshd.orig"
run_command "cat > /etc/pam.d/sshd << EOF
# auth
auth            sufficient      pam_opie.so                     no_warn no_fake_prompts
auth            requisite       pam_opieaccess.so               no_warn allow_local
auth            sufficient      pam_krb5.so                     no_warn try_first_pass
#auth           sufficient      pam_ssh.so                      no_warn try_first_pass
auth            sufficient      pam_unix.so                     no_warn try_first_pass nullok
auth            required        /usr/local/lib/pam_winbind.so   try_first_pass

# account
account         required        pam_nologin.so
account         required        pam_krb5.so
account         required        pam_login_access.so
account         required        pam_unix.so

# session
#session        optional        pam_ssh.so
session         required        /usr/local/lib/pam_mkhomedir.so
session         required        pam_permit.so           no_fail

# password
password        sufficient      pam_krb5.so             no_warn try_first_pass
password        required        pam_unix.so             no_warn try_first_pass
EOF"
run_command "cp /etc/pam.d/sshd /etc/pam.d/sshd.ad"
run_command "echo \"AllowGroups wheel localadmin_${FULL_COMPUTERNAME}\" >> /etc/ssh/sshd_config"
run_command "sed -i '' -e \"/root ALL=(ALL) ALL/{G;s/$/admin ALL=(ALL) ! ALL/;}\" -e \"/admin ALL=(ALL) ! ALL/{G;s/$/replicator ALL=(ALL) ! ALL/;}\" -e \"/# %wheel ALL=(ALL) ALL/{G;s/$/%localadmin_${FULL_COMPUTERNAME} ALL=(ALL) ALL/;}\" /usr/local/etc/sudoers"
run_command "cat >> /etc/rc.conf << EOF
samba_enable=\"YES\"
winbindd_enable=\"YES\"
EOF"
read -r -p '+-- Enter user id used to join domain: ' JOINACCOUNT
net ads join -U ${JOINACCOUNT}
if [ $? -gt "0" ]; then
  echo "+-- Failed in running command:"
  echo "net ads join -U ${JOINACCOUNT}"
  echo ""
  exit 1
fi
if service samba status | grep -q "is not running"; then
  run_command "service samba start"
else
  run_command "service samba restart"
fi
run_command "zfs create -o mountpoint=/export -o compression=lz4 -o canmount=noauto -o utf8only=on -o sync=always pool2/export"
run_command "zfs create -o mountpoint=/export/ds1 -o compression=lz4 -o canmount=noauto -o utf8only=on -o sync=always pool2/ds1"
run_command "zfs create -o mountpoint=/export/ds2 -o compression=lz4 -o canmount=noauto -o utf8only=on -o sync=always pool2/ds2"
run_command "cat >> /etc/fstab << EOF
pool2/export		/export		zfs	rw	0	0
pool2/ds1		/export/ds1	zfs	rw	0	0
pool2/ds2		/export/ds2	zfs	rw	0	0
EOF"
run_command "zfs mount pool2/export"
run_command "zfs mount pool2/ds1"
run_command "zfs mount pool2/ds2"
run_command "cat >> /etc/exports << EOF
/export/ds1		-maproot=root
/export/ds2             -maproot=root
EOF"
run_command "cat >> /etc/rc.conf << EOF
rpcbind_enable=\"YES\"
nfs_server_enable=\"YES\"
nfs_server_flags=\"-u -t -n 4\"
mountd_enable=\"YES\"
mountd_flags=\"-r -S\"
EOF"
if service rpcbind status | grep -q "is not running"; then
  run_command "service rpcbind start"
else
  run_command "service rpcbind restart"
fi
if service nfsd status | grep -q "is not running"; then
  run_command "service nfsd start"
else
  run_command "service nfsd restart"
fi
if service mountd status | grep -q "is not running"; then
  run_command "service mountd start"
else
  run_command "service mountd restart"
fi
run_command "zfs create -o mountpoint=/export/slu_storage -o compression=lz4 -o aclmode=passthrough -o aclinherit=passthrough -o canmount=noauto -o utf8only=on -o sync=always pool2/slu_storage"
run_command "zfs create -o canmount=noauto pool2/slu_storage/common"
run_command "zfs create -o canmount=noauto pool2/slu_storage/home"
run_command "zfs create -o canmount=noauto pool2/slu_storage/profile"
run_command "cat >> /etc/fstab << EOF
pool2/slu_storage		/export/slu_storage		zfs	rw	0	0
pool2/slu_storage/common	/export/slu_storage/common	zfs	rw	0	0
pool2/slu_storage/home		/export/slu_storage/home	zfs	rw	0	0
pool2/slu_storage/profile	/export/slu_storage/profile	zfs	rw	0	0
EOF"
run_command "zfs mount pool2/slu_storage"
run_command "zfs mount pool2/slu_storage/common"
run_command "zfs mount pool2/slu_storage/home"
run_command "zfs mount pool2/slu_storage/profile"
LOCAL_ADMIN_SID=$(net groupmap list | awk '/Administrators/ {gsub(/\(/, ""); gsub(/\)/, ""); print $2}')
DOMAIN_LOCAL_ADMIN_SID=$(wbinfo -G $(wbinfo --group-info=localadmin_${FULL_COMPUTERNAME} | awk -F ':' '{print $3}'))
run_command "net groupmap addmem ${LOCAL_ADMIN_SID} ${DOMAIN_LOCAL_ADMIN_SID}"
run_command "sed -i '' 's/template homedir = \/usr\/home\/%U/template homedir = \/export\/slu_storage\/home\/%U/' /usr/local/etc/smb.conf"
run_command "cat >> /usr/local/etc/smb.conf << EOF

        max protocol = SMB2
        display charset = UTF-8

        socket options = TCP_NODELAY SO_SNDBUF=131072 SO_RCVBUF=131072
        use sendfile = no
        min receivefile size = 16384
        aio read size = 16384
        aio write size = 16384
        aio write behind = yes

        unix extensions = no

        full_audit:prefix = %u|%I|%S
        full_audit:failure = connect
        full_audit:success = connect disconnect opendir mkdir rmdir closedir open close read pread write pwrite sendfile rename unlink chmod fchmod chown fchown chdir ftruncate lock symlink readlink link mknod realpath
        full_audit:facility = local5
        full_audit:priority = notice

[common$]
        comment = Network Common Directory
        path = /export/slu_storage/common
        writable = yes
        csc policy = disable
        create mask = 600
        directory mask = 0700
        vfs objects = full_audit, shadow_copy2, zfsacl
        shadow: snapdir = .zfs/snapshot
        shadow: sort = desc
        shadow: localtime = yes
        shadow: format = auto-%Y-%m-%d_%H.%M.%S--28d
        nfs4:acedup = merge
        nfs4:mode = special
        nfs4:chown = yes
        follow symlinks = yes
        wide links = yes
        nt acl support = yes
        map acl inherit = yes
        inherit acls = yes
        inherit permissions = yes
        inherit owner = yes
        ea support = yes
        store dos attributes = yes
        map hidden = no
        map system = no
        map archive = no
        case sensitive = no

[home$]
        comment = Network Home Directory
        path = /export/slu_storage/home
        writable = yes
        create mask = 600
        directory mask = 0700
        valid users = %U
        vfs objects = full_audit, shadow_copy2, zfsacl
        shadow: snapdir = .zfs/snapshot
        shadow: sort = desc
        shadow: localtime = yes
        shadow: format = auto-%Y-%m-%d_%H.%M.%S--28d
        nfs4:acedup = merge
        nfs4:mode = special
        nfs4:chown = yes
        follow symlinks = yes
        wide links = yes
        nt acl support = yes
        map acl inherit = yes
        inherit acls = yes
        inherit permissions = yes
        inherit owner = no
        ea support = yes
        store dos attributes = yes
        map hidden = no
        map system = no
        map archive = no
        case sensitive = no

[profile$]
        comment = Network Profile Directory
        path = /export/slu_storage/profile
        writeable = yes
        create mask = 600
        directory mask = 0700
        csc policy = disable
        valid users = %U @\"domain admins\"
        vfs objects = full_audit, shadow_copy2, zfsacl
        shadow: snapdir = .zfs/snapshot
        shadow: sort = desc
        shadow: localtime = yes
        shadow: format = auto-%Y-%m-%d_%H.%M.%S--28d
        nfs4:acedup = merge
        nfs4:mode = special
        nfs4:chown = yes
        follow symlinks = yes
        wide links = yes
        nt acl support = yes
        map acl inherit = yes
        inherit acls = yes
        inherit permissions = yes
        inherit owner = no
        ea support = yes
        store dos attributes = yes
        map hidden = no
        map system = no
        map archive = no
        case sensitive = no


[ds1$]
        comment = Datastore 1
        path = /export/ds1
        writable = yes
        csc policy = disable
        valid users = @\"localadmin_${FULL_COMPUTERNAME}\"
        vfs objects = shadow_copy2, zfsacl
        shadow: format = auto-%Y-%m-%d_%H.%M.%S--28d
        shadow: sort = desc
        shadow: snapdir = .zfs/snapshot
        nfs4:acedup = merge
        nfs4:mode = special
        nfs4:chown = yes
        follow symlinks = yes
        wide links = yes
        nt acl support = no 
        map acl inherit = no 
        inherit acls = no 
        inherit permissions = yes
        inherit owner = yes
        ea support = yes
        store dos attributes = no 
        map hidden = no
        map system = no
        map archive = no
        case sensitive = no

[ds2$]
        comment = Datastore 2
        path = /export/ds2
        writable = yes
        csc policy = disable
        valid users = @\"localadmin_${FULL_COMPUTERNAME}\"
        vfs objects = shadow_copy2, zfsacl
        shadow: format = auto-%Y-%m-%d_%H.%M.%S--28d
        shadow: sort = desc
        shadow: snapdir = .zfs/snapshot
        nfs4:acedup = merge
        nfs4:mode = special
        nfs4:chown = yes
        follow symlinks = yes
        wide links = yes
        nt acl support = no
        map acl inherit = no
        inherit acls = no
        inherit permissions = yes
        inherit owner = yes
        ea support = yes
        store dos attributes = no
        map hidden = no
        map system = no
        map archive = no
        case sensitive = no
EOF"
run_command "pkg install -y netatalk3 avahi"
run_command "cat > /etc/pam.d/netatalk << EOF
auth		sufficient	pam_unix.so			try_first_pass
auth		required	/usr/local/lib/pam_winbind.so	cached_login use_first_pass

account		sufficient	pam_unix.so			try_first_pass
account		required        /usr/local/lib/pam_winbind.so	use_first_pass

password	sufficient	pam_unix.so			no_warn try_first_pass use_authtok
password	required	/usr/local/lib/pam_winbind.so	use_authtok

session         required        /usr/local/lib/pam_mkhomedir.so
session		required	pam_permit.so			no_fail
EOF"
run_command "cat > /usr/local/etc/avahi/services/afp.service << EOF
<?xml version=\"1.0\" standalone='no'?><!--*-nxml-*-->
<!DOCTYPE service-group SYSTEM \"avahi-service.dtd\">

<service-group>
  <name replace-wildcards=\"yes\">%h</name>

  <service>
    <type>_afpovertcp._tcp</type>
    <port>548</port>
  </service>

  <service>
    <type>_device-info._tcp</type>
    <port>0</port>
    <txt-record>model=Xserve</txt-record>
  </service>

</service-group>
EOF"
run_command "cat > /usr/local/etc/afp.conf << EOF
;
; Netatalk 3.x configuration file
;

[Global]
 hostname = ${FULL_COMPUTERNAME}
 mimic model = Xserve
 map acls = mode
 vol charset = UTF8
 log file = /var/log/afpd.log

[Homes]
 basedir regex = /export/slu_storage/home
 file perm = 600
 directory perm = 0700

[Network Common Directory]
 path = /export/slu_storage/common
 file perm = 600                                                                            
 directory perm = 0700
EOF"
run_command "setfacl -m owner@:rwxpdDaARWcCos:fd:allow /export/slu_storage/*"
run_command "setfacl -m group@::fd:allow /export/slu_storage/*"
run_command "setfacl -m everyone@::fd:allow /export/slu_storage/*"
run_command "setfacl -m group:BUILTIN\\\\administrators:rwxpdDaARWcCos:fd:allow /export/slu_storage/*"
run_command "setfacl -m group:BUILTIN\\\\administrators:rwxpdDaARWcCos:fd:allow /export/ds*"
run_command "cat >> /etc/rc.conf << EOF
dbus_enable=\"YES\"
avahi_daemon_enable=\"YES\"
afpd_enable=\"YES\"
netatalk_enable=\"YES\"
cnid_metad_enable=\"YES\"
EOF"
if service samba status | grep -q "is not running"; then
  run_command "service samba start"
else
  run_command "service samba restart"
fi
if service dbus status | grep -q "is not running"; then
  run_command "service dbus start"
else
  run_command "service dbus restart"
fi
if service avahi-daemon status | grep -q "is not running"; then
  run_command "service avahi-daemon start"
else
  run_command "service avahi-daemon restart"
fi
if service netatalk status | grep -q "is not running"; then
  run_command "service netatalk start"
else
  run_command "service netatalk restart"
fi
run_command "cat >> /etc/periodic.conf << EOF
hourly_zfsnap_enable=\"YES\"
hourly_zfsnap_enable_prefix=\"YES\"
hourly_zfsnap_prefix=\"auto-\"
hourly_zfsnap_ttl=\"28d\"
hourly_zfsnap_fs=\"pool2/slu_storage/common pool2/slu_storage/home pool2/slu_storage/profile\"
hourly_zfsnap_flags=\"-z -s -S\"
daily_zfsnap_enable=\"YES\"
daily_zfsnap_enable_prefix=\"YES\"
daily_zfsnap_prefix=\"auto-\"
daily_zfsnap_ttl=\"28d\"
daily_zfsnap_fs=\"pool2/ds1 pool2/ds2\"
daily_zfsnap_flags=\"-z -s -S\"
EOF"
run_command "sed -i '' \"/# Perform daily\/weekly\/monthly maintenance./{G;s/$/0       *       *       *       *       root    periodic hourly/;}\" /etc/crontab"
if [ $(zfs list -o name | grep -c 'pool1/root') -ne 0 ]; then
  run_command "zfs set readonly=on pool1/root"
fi
