#!/bin/ksh
#!/bin/sh
# Create New Wolrd in s4
# Arguments:
#   $1 = World Display Name in UTF-8
#   $2 = World ShortName in alpha-numeric
#   $3 = World Description in UTF-8
dispname=$1
shortname=$2
desc=$3

readvar() {	# $1=varname $2=PromptString
  echo -n "${2:-$1=:} "
  read $1
}

if [ -z "$HTTP_HOST" ]; then
  while true; do
    dispname=`echo $dispname | tr -d ': \t\n"' | fold -w 28 | head -1`
    test -n "$dispname" && break
    readvar dispname "分かりやすいWorld名14字以内"
  done
  while true; do
    shortname=`echo $shortname | tr -c -d '_0-9A-Za-z.-' | colrm 11`
    test -n "$shortname" && break
    readvar shortname "英数字のみ10字以内のWorldシンボル(URLの一部)"
  done
  while true; do
    desc=`echo $desc | tr -d ': \t\n"'`
    test -n "$desc" && break
    readvar desc "概要(どのような基準でこのWorldを使うかなど)"
  done
fi
echo "wl=$S4WORLDLIST"
echo "$dispname:$shortname:$desc"
# Create config
DB=db/$shortname.sq3; export DB
`dirname $0`/s4-init.sh
. `dirname $0`/s4-config.sh
if ! type htmlescape >/dev/null 2>&1; then
  . `dirname $0`/s4-funcs.sh ### > /dev/null 2>&1
  trap 'exit 1' INT QUIT
fi

newworld=$(
  { echo $S4WORLDLIST | tr ' ' '\n' \
      | awk -F: "\$2 != \"$shortname\"{print}"
    echo "$dispname:$shortname:$desc"
  } | tr '\n' ' ' | sed 's/ $//' | tr -d '"'
	)
if [ -z "$newworld" ]; then
  exit
fi

masterdb=`(unset DB; . ./s4-config.sh; echo $DB)`
S4MASTERDB=${masterdb:-db/cgi.sq3}
echo Synching account: db=$db URL=$URL isCGI=$isCGI mas=$S4MASTERDB
. ./s4-world.sh && syncaccount 'force'
echo Synching done
bgcolor=$(
  od -An -tu1 -N3 < /dev/urandom \
    | { read r g b
	r=$((192+r/4)); g=$((192+g/4)); b=$((192+b/4))
	printf "#%x%x%x" $r $g $b
  })
cat<<-EOF > s4-config-$shortname.sh
	S4MASTERURL=\$URL
	URL=`dirname ${URL}.`/s4-world-$shortname$cgiext
	S4COLOR="$bgcolor"			# Change this!
	DB=$dbdir/$shortname.sq3
	SESSDB=$dbdir/sess.sq3
	S4MASTERDB=$db
	S4CSS=$shortname.css
	TMPDIR=$tmpdir/$shortname
EOF
# Create CSS
cat<<-EOF > $shortname.css
	body {background: $bgcolor;}
	body.moderated {background: $bgcolor; border: 3px gold solid;}
EOF
mkdir -m 1775 $tmpdir/$shortname
# Update s4-config.sh
cat<<-EOF | ed s4-config.sh
	g/^S4WORLDLIST=/d
	wq
EOF
echo "S4WORLDLIST=\"$newworld\"" >> s4-config.sh

(cd `dirname $0`; ln -s s4$cgiext s4-world-$shortname$cgiext)
echo $newworld added
