#! /bin/sh

HOST="http://download.zeronews.cc"
ZR_VERSION=1.3.12

start_zeronews() {

  token=$1
  area=$2

  ret=$(zeronews set-token $token)
  echo "$ret"
  if [ "$ret" != *success* ];then
    exit 1
  fi

  zeronews set-area $area > /dev/null

  /etc/init.d/zeronews start
  echo "zeronews is running ..."

}

remove_zeronews() {

  ps -ef|grep zeronews |grep -v grep|awk '{print $2}'|xargs kill -9
  /etc/init.d/zeronews stop >/dev/null 2>&1

  rm -rf /usr/bin/zeronews  >/dev/null 2>&1
  rm -rf /etc/init.d/zeronews  >/dev/null 2>&1
  rm -rf /etc/rc.d/S80zeronews  >/dev/null 2>&1
  sync
  echo "zeronews is delete"

}

zeronews_download() {

  cd /tmp/zeronews_tmp
  if command -v curl >/dev/null 2>&1; then
    echo "-SLk $1 -o zeronews.tar"
    curl -SLk $1 -o zeronews.tar

  elif command -v wget >/dev/null 2>&1; then
    echo "wget --no-check-certificate $1"
    wget --no-check-certificate $1

  fi

}

zeronews_pkg_url() {
  . /etc/os-release
  TYPE=$(uname -m)

  echo "$TYPE"
  pgk=zeronews-openwrt-$ZR_VERSION.tar
  download_url=""
  if $(echo $TYPE |grep -Eqi "x86_64"); then
    download_url="${HOST}/openwrt/x86_x64/$pgk"

  elif $(echo $TYPE |grep -Eqi "arm"); then
    download_url="${HOST}/openwrt/arm/$pgk"

  elif $(echo $TYPE |grep -Eqi "aarch64"); then
    download_url="${HOST}/openwrt/arm64/$pgk"

  elif $(echo $TYPE |grep -Eqi "mips"); then
    download_url="${HOST}/openwrt/mips/$pgk"
  fi

  if [ -n $download_url ]; then
    echo $download_url
    zeronews_download $download_url
  fi

}

install_zeronews() {
  . /etc/os-release
  rm -rf /tmp/zeronews_tmp  > /dev/null 2>&1
  mkdir /tmp/zeronews_tmp
  echo "install zeronews client"
  if [ -e "zeronews.tar" ];then
    cp zeronews.tar /tmp/zeronews_tmp
  else
    zeronews_pkg_url
  fi

  /etc/init.d/zeronews stop > /dev/null 2>&1

  cd /tmp/zeronews_tmp
  tar -xvf zeronews.tar

  rm -rf /usr/bin/zeronews  >/dev/null 2>&1
  rm -rf /etc/init.d/zeronews >/dev/null 2>&1

  cp zeronews/zeronews /usr/bin/
  cp zeronews/init.d/zeronews /etc/init.d/zeronews

  cd /etc/rc.d
  rm -rf S80zeronews  >/dev/null 2>&1
  ln -s ../init.d/zeronews S80zeronews
  cd /tmp
  rm -rf /tmp/zeronews_tmp
  echo "zeronews install success"

  sync

  if [ $2 ] && [ $3 ];then
    start_zeronews $2 $3
  fi
}

menu() {
  case $1 in
    install)
      install_zeronews $1 $2 $3
      ;;
    remove)
      remove_zeronews
      ;;
    --help|-h)
      echo ""
      echo "Welecome to zeronews client install scripts"
      echo ""
      echo "Usage:"
      echo "  install.sh [command]"
      echo ""
      echo "Available Commands:"
      echo "  install [token_id] [area_id]    install zeronews client and set auth token and zeronews network area"
      echo "  remove     delete zeronews client"
      echo ""
      echo "Flags:"
      echo "-h, --help   help for zeronews"
      ;;
  esac
}

menu $1 $2 $3
