#
# cgi functions
#
cgi_form() {
  # $1=stage
  : ${myname:?'Sure to set $myname to this script name'}
  cont=`cat`
  cat<<EOF
<form action="$myname" method="POST" enctype="multipart/form-data">
$cont
<input type="hidden" name="stage" value="$1">
<input type="submit" value="送信">
<input type="reset" value="リセット">
</form>
EOF
}
cgi_submit() {
  cat<<EOF
<input type="submit" value="$1">
EOF
}
cgi_reset() {
  cat<<EOF
<input type="reset" value="$1">
EOF
}
cgi_radio() {
  echo "<input type=\"radio\" name=\"$1\" ${2:+value=\"$2\"} $3>"
}
cgi_checkbox() {
  echo "<input type=\"checkbox\" name=\"$1\" ${2:+value=\"$2\"} $3>"
}
cgi_hidden() {
  echo "<input type=\"hidden\" name=\"$1\" value=\"$2\" $3>"
}
cgi_passwd() {
  cat<<EOF
<table class="pswd">
 <tr><td>現パスワード</td><td><input type="password" name="pswd"></td></tr>
 <tr><td>新パスワード</td><td><input type="password" name="pswd1"></td></tr>
 <tr><td>新パスワード(確認)</td><td><input type="password" name="pswd2"></td></tr>
</table>
EOF
}
cgi_text() {
  echo "<input type=\"text\" name=\"$1\" value=\"$2\" $3>"
}
cgi_textarea() {
  cat<<EOF
<textarea name="$1" $3>$2</textarea>
EOF
}
cgi_file() (			# In a subshell
  # $1=name $2=val(as filename) $3=args(if any)
  # Using global variable $dir
  if [ -s $dir/$2 -a -s $dir/$2.content-type ]; then
    file=$dir/$2
    bn=${file##*/}
    ct=`cat $dir/$2.content-type`
    data=`percenthex $file`
    icon="<img src=\"data:$ct,$data\">"
  fi
  cat<<EOF
 ${icon}
<input type="file" name="$1" value="$bn" $3>
EOF
)
cgi_multi() (
  # $1=name $2=dir $3=func $4=args...
  # `dir' should contain $name.count and $name.N where N is 1 upto N
  i=1 name=$1 dir=$2 func=$3
  n=`cat $dir/$name.count`
  echo '<table class="text">'
  while [ $i -le $n ]; do
    file=$name.$i	ctf=$dir/$name.content-type
    vname=$file.`cat $dir/$file.rowid`
    if [ -s $ctf ]; then
      case `cat $ctf` in
	*:[Ii]mage:*)
	  
	;;
	
      esac
    fi
    val="`cat $dir/$file`"
    cat<<EOF
 <tr><td>($i)</td><td>
<input class="action" type="radio" name="action.$vname" id="keep.$vname"
 value="keep"><label for="keep.$vname">温存</label>
<input class="action" type="radio" name="action.$vname" id="edit.$vname"
 value="edit"><label for="edit.$vname">修正</label>
<input class="action" type="radio" name="action.$vname" id="rm.$vname"
 value="rm"><label for="rm.$vname">削除</label>
<label class="confirm">本当に消します<input class="confirm" type="checkbox"
 name="confirm.$vname" value="yes">はい</label><br>
`$func $vname "$val" "$4"`<span>$val</span>
</td></tr>
EOF
    i=$((i+1))
  done
  cat<<EOF
 <tr><td>(新規)</td><td>`$func $name "" "$4"`</td></tr>
</table>
EOF
)
# In these functions, $2 should be quoted because it can be null
cgi_multi_text() {
  cgi_multi $1 "$2" cgi_text "$3"
}
cgi_multi_textarea() {
  cgi_multi $1 "$2" cgi_textarea "$3"
}
cgi_multi_file() {
  # $1=name $2=val(filename)
  cgi_multi $1 "$2" cgi_file "$3"
}

html() {
  echo "<$*>"
  cat
  echo "</$1>"
}
