#!/bin/sh
set -e

usage () {
  exec 1>&2
  echo "Usage: $0 acct logacct /etc/tinydyn myip mydomain"
  exit 1
}

if [ $# -ne 5 ]; then usage; fi

cwd=`pwd`
acct=$1
logacct=$2
dir=$3
ip=$4
mydomain=$5

acct_uid=`id -u $acct`
acct_gid=`id -g $acct`
logacct_uid=`id -u $logacct`

tinydns-conf $acct $logacct $dir $ip

cd $dir

# data file
cd root
./add-ns $mydomain $ip
./add-alias $mydomain $ip
chown $acct . data
make
chown $acct data.cdb

# modify Makefile
cat <<EOT >Makefile'{new}'
default:
	@echo 'tinydyndns modifies the binary database data.cdb directly. Use'
	@echo "'make rebuild' to rebuild data.cdb with a NS, SOA, A record for"
	@echo 'the nameserver, and A records for all dynamic hostnames in the'
	@echo 'local passwd database, pointing to the IP address 127.14.14.14.'
	@echo

EOT
cat Makefile >>Makefile'{new}'
cat <<EOT >>Makefile'{new}'

rebuild: clean data.cdb
	cut -d: -f1 <../pop/passwd |sed -e 's/\$\$/.${mydomain}/' \\
	  |xargs tinydyndns-data add

clean:
	rm -f data.cdb
EOT
mv -f Makefile'{new}' Makefile

cd ..

# pop3
mkdir -p pop
chown $acct pop
chmod 750 pop
cd pop
cat <<EOF >run
#!/bin/sh
exec softlimit -m 4000000 envdir ./env tcpserver -vRH $ip 110 \\
  /var/qmail/bin/qmail-popup $mydomain \\
    cvm-checkpassword cvm-pwfile sh -c '
      echo "login: \$USER: \$TCPREMOTEIP" >&7
      cd $dir/root
      /command/setlock data.cdb \\
      tinydyndns-update \${USER}.$mydomain \$TCPREMOTEIP >&7 2>&1
      cd $dir/pop
      exec /var/qmail/bin/qmail-pop3d Maildir
    ' 2>&1 7>&1
EOF
chmod 750 run

touch passwd
chown $acct passwd

# setpasswd script
cat <<EOF >setpasswd
#!/bin/sh
if [ -z "\$1" -o -z "\$2" ]; then echo "Usage: \$0 host passwd" >&2; exit; fi
HOST=\$1
PASSWD=\$2
if ! grep "^\$HOST:" $dir/pop/passwd >/dev/null; then
  cat $dir/pop/passwd >$dir/pop/passwd'{new}'
  echo "\$HOST:\$PASSWD:$acct_uid:$acct_gid::$dir/pop:/bin/false" \\
    >>$dir/pop/passwd'{new}'
else
  sed -e \\
    "s}^\$HOST:.*$}\$HOST:\$PASSWD:$acct_uid:$acct_gid::$dir/pop:/bin/false}g" \\
      $dir/pop/passwd >$dir/pop/passwd'{new}'
fi
mv -f $dir/pop/passwd'{new}' $dir/pop/passwd
chmod 600 $dir/pop/passwd
( cd $dir/root; tinydyndns-data add \${HOST}.$mydomain )
EOF
chmod 750 setpasswd
chown $acct setpasswd

# envdir
mkdir -p env
chmod 750 env
echo "$dir/pop/passwd" >env/CVM_PWFILE_PATH
echo 'plain' >env/CVM_PWFILE_PWCMP

# Maildir
echo '|bouncesaying \'This address does not accept mail.\' >.qmail
maildirmake Maildir || true
chown -R $acct Maildir

# logdir
mkdir -p log
chown $logacct log
chmod 750 log
cd log
cat <<EOF >run
#!/bin/sh
exec setuidgid $logacct multilog t ./main
EOF
chmod 750 run

cd $cwd
exit 0
