#!/bin/sh

### BEGIN INIT INFO
# Provides:          ftpd
# Required-Start:    $network $local_fs $remote_fs
# Required-Stop:     $network $local_fs $remote_fs
# Default-Start:     2 3 4 5
### END INIT INFO

. /etc/init.d/functions

ter_ftp_cfg=/usr/tos/bin/ter_ftp_cfg
service="smbftpd"
extconf="/etc/smbftpd/smbftpd.conf"
sslpath="/etc/ssl/smbftpd"
execute="/usr/sbin/smbftpd"
exeopts="-D -s $extconf"
ssljson="/etc/ssls/selected_ssl.json"

service_prepare() {
  [ ! -d /var/empty ] && mkdir -p /var/empty
  df-json | grep -E '/Volume[0-9]+' >/dev/null
  if [ $? -ne 0 ]; then
    echo "There is no disk mounted!"
    exit 1
  fi
  $ter_ftp_cfg >/dev/null 2>&1
  [ ! -d /tmp/TOS_CONFIG/zlog/ ] && mkdir -p /tmp/TOS_CONFIG/zlog/
  cp -a /etc/zlog/zlog_smbftp.conf /tmp/TOS_CONFIG/zlog/
  chmod 777 /var/log/zlog/.
  [ ! -d $sslpath ] && mkdir -p $sslpath
  replacestr $extconf "ServerName" "ServerName $(hostname)"

  #genrate smbftpd ssl certificate
  if [ ! -f $sslpath/server.crt ] && [ ! -f $sslpath/server.key ]; then
    openssl req \
      -new -x509 -nodes \
      -out $sslpath/server.crt \
      -subj "/C=US/ST=California/L=SanFrancisco/O=Dis/CN=www.terra-master.com" \
      -keyout $sslpath/server.key
  fi

  sed -i '/^SSLCertFile/d;/^SSLKeyFile/d' $extconf
  printf "SSLKeyFile %s\nSSLCertFile %s \n" $sslpath/server.key $sslpath/server.crt >>$extconf

  replacestr $extconf "NoLoginList" "NoLoginList /etc/pam_conf/FTP"
  # read json to sed ssl
  if [ -f ${ssljson} ]; then
    KEY=$(jq -r .FTP.key $ssljson)
    PEM=$(jq -r .FTP.pem $ssljson)
    if [ "$KEY" != null ] && [ "$PEM" != null ]; then
      sed -i '/^SSLCertFile/d;/^SSLKeyFile/d' $extconf
      printf "SSLKeyFile %s\nSSLCertFile %s \n" "$KEY" "$PEM" >>$extconf
    fi
  fi
  #

  /sbin/ftpdconf
}


service_prepare
