#!/bin/sh
MTYDIR="/home/mty"
MTYSTDERR="stderr.log"
MTYLOG="log.txt"
MTYTARG="target.txt"
CONFDIR="/home/config"

mtystart()
{
  ./mty > /dev/null 2> "$MTYSTDERR" &
}

mtystop()
{
  PSRES="`pgrep -x mty`"
  if [ "$PSRES" != "" ]; then
    kill $PSRES
  fi
}

mtystatus()
{
  PSRES="`pgrep -x mty`"
  if [ "$PSRES" != "" ]; then
#    ps up $PSRES
    ps -o pcpu,pmem,start,comm -p $PSRES
  else
    echo "動いていません。"
  fi
}

htmlhead()
{
  cat << EOHTMLHEAD
Content-type: text/html

<html>
 <head>
  <title>$1</title>
 </head>

 <body bgcolor="fff8e7" text="000000">
 <pre>
EOHTMLHEAD
}

htmltail()
{
  cat << EOHTMLTAIL
 </pre>
 </body>
</html>
EOHTMLTAIL
}

main()
{
  cd "$MTYDIR"

  case "$0" in
    *mtystart)
      htmlhead 開始
      mtystop
      mtystart
      mtystatus
      htmltail
      ;;
    *mtystop)
      htmlhead 停止
      mtystop
      echo "停止させました。"
      htmltail
      ;;
    *mtystatus)
      htmlhead 様子見
      mtystatus
      htmltail
      ;;
    *mtyspeed)
      htmlhead 速度など
      iconv -f CP932 -t utf-8 "$MTYSTDERR"
      htmltail
      ;;
    *mtylog)
      htmlhead 検索結果
      if [ -s "$MTYLOG" ]; then
        iconv -f CP932 -t utf-8 "$MTYLOG"
      else
        echo "まだなにもありません。"
      fi
      htmltail
      ;;
    *mtydel)
      htmlhead "log.txt の削除"
      PSRES="`pgrep -x mty`"
      if [ "$PSRES" != "" ]; then
        echo "待て屋を止めないと消せません。"
      else
#       TS="`date "+%Y%m%d%H%M%S"`"
#       mv "$MTYLOG" "$MTYLOG"."$TS"
        rm "$MTYLOG"
        echo "削除しました。"
      fi
      htmltail
      ;;
    *mtyup)
      awk '{
        gsub( "\r", "", $0 );
        if ( NR == 1 ) {
         delmline = $0;
         getline;
         getline;
         getline;
        } else if ( match( $0, delmline ) == 0 ) {
         printf( "%s\n", $0 );
        }
      }' > "$MTYTARG"
      htmlhead "target.txt の転送"
      echo "target.txt を転送して、検索を開始しました。"
      mtystop
      mtystart
      mtystatus
      htmltail
      ;;
    *mtysetup)
      htmlhead "このシステムの更新"
      sudo /bin/chmod +x $CONFDIR/setup
      sudo $CONFDIR/setup
      sudo /bin/rm $CONFDIR/setup
      htmltail
      ;;
  esac
}

main ${1+"$@"}
exit 0
