#!/bin/bash

set -o nounset

# Check if dupload is installed
INSTALLED=`dpkg -l dupload 2>/dev/null | grep -Ec "^ii\s+dupload"`
if [ $INSTALLED -eq 0 ]
then
cat << EOF
  dupload package is missing, you must install it.
  You can use dupload.conf-sample file and copy it
  to ~/.dupload.conf or copy parts to your .dupload.conf
  file.
EOF
  exit 0
fi

# Running from debian parent dir ?
[ ! -d ./debian ] && echo "Not running from debian parent dir, end of script." && exit 0

MY_PATH="$( cd "$(dirname "$0")" ; pwd -P )"
CONF_FILE="${MY_PATH}/ee-package-uploader.conf"

# Source config file {{{
if [ -e ${CONF_FILE} ]
then
  source ${CONF_FILE}
else
cat << EOF
  Config file ${CONF_FILE} missing!
  Take à look at ${CONF_FILE}-sample,
  You can copy it to ${CONF_FILE} and modify as your needs.
  End of script, exiting.
EOF
  exit 0
fi
#}}}

# Define syntax highlight colors {{{
bold="`tput setaf 3`"
norm="`tput sgr0`"
green="`tput setf 2`" 
blue="`tput setf 1`"
# }}}

# Get Package name, version and dist from Debian Changelog
read PKG VERS REPREPRO_DIST < <(head -1 debian/changelog  | cut -d';' -f 1 | sed 's/[\(|\)]//g' | cut -d " " -f 1-3)

# Set environment, prod, preprod or dev {{{
set_env () {

  local _ENV=$1

  case ${_ENV} in
    prod)
      read BACKEND REPREPRO_DIR DUPLOAD_DIST EE_REPREPRO_MIRROR < <(echo ${ENV_PROD[*]})
      ;;
    preprod)
      read BACKEND REPREPRO_DIR DUPLOAD_DIST EE_REPREPRO_MIRROR < <(echo ${ENV_PREPROD[*]})
      ;;
    dev)
      read BACKEND REPREPRO_DIR DUPLOAD_DIST EE_REPREPRO_MIRROR < <(echo ${ENV_DEV[*]})
      ;;
  esac

  echo ${_ENV}
}
#}}}

# Cleanup reprepro {{{
function cleanup_reprepro () {

  echo -e "\n\t${green}Running $FUNCNAME: ssh ${REPREPRO_CONNECTION}\n${norm}"

  ssh ${REPREPRO_CONNECTION} <<ENDSSH

export TERM=LINUX
cd $REPREPRO_DIR
reprepro -V remove $REPRERPO_DIST ${PKG}
reprepro -V deleteunreferenced

ENDSSH

}
#}}}

# Build package {{{
function build_package () {

  echo -e "\n\t${green}Running $FUNCNAME: rm -f ../${PKG}_${VERS}*\n${norm}"
  rm -f ../${PKG}_${VERS}*

  echo -e "\n\t${green}Running $FUNCNAME: dpkg-buildpackage\n${norm}"
  dpkg-buildpackage
  res=$?
  [ $res -ne 0 ] && echo "${blue}error: $res.${norm}" && exit 0 
}
#}}}

# Cleanup and push to reprepro {{{
function push_reprepro () {

  [ "${BUILD_PACKAGE}" == "yes" ] && build_package

  if [ ! -f ../${PKG}_${VERS}_amd64.changes ]
  then
    echo "../${PKG}_${VERS}_amd64.changes is missing, end of script"
    exit 0
  fi

  cleanup_reprepro

  echo -e "\n\t${green}Running $FUNCNAME: dupload --to $DUPLOAD_DIST ../${PKG}_${VERS}_amd64.changes\n${norm}"
  dupload --to $DUPLOAD_DIST ../${PKG}_${VERS}_amd64.changes
  res=$?
  [ $res -gt 1 ] && echo "${blue}error: $res.${norm}" && exit 0

  [ "${UPDATE_MIRROR}" == "yes" ] && update_mirror
}
#}}}

# Update mirror fetching from this reprepro {{{
function update_mirror () {

  echo -e "\n\t${green}Running $FUNCNAME: ssh ${MIRROR_REPREPRO_CONNECTION}\n${norm}"

  ssh ${MIRROR_REPREPRO_CONNECTION} <<ENDSSH

export TERM=LINUX

cd ${EE_REPREPRO_MIRROR}
reprepro -V remove stretch-ee ${PKG}
reprepro -V deleteunreferenced

/usr/local/bin/updatemirror.sh ${EE_REPREPRO_MIRROR}
#cd $REPREPRO_DIR
#reprepro -V remove $REPRERPO_DIST ${PKG}
#reprepro -V update

ENDSSH


}
#}}}
# Get servers list {{{
function get_list () {

  echo

  for pos in `seq 0 ${SRV_LIST_END}`
  do
    if [ $(( $pos % 2)) -eq 0 ]
    then
      color=$norm
    else
      color=$bold
    fi
    echo -e "${color}[$pos] ${SRV_LIST[$pos]/:/:\\t\\t}"
  done

  echo $norm

}
#}}}

# Cleanup apt-cacher cache via ssh {{{
function ssh_rmcache () {

  for connection in "${SRV_LIST[@]}"
  do
    echo -e "\n\t${green}Running $FUNCNAME: ${connection/*: /}\n${norm}"
    ${connection/*: /}  <<ENDSSH

export TERM=LINUX
sudo -i bash -s

/etc/init.d/apt-cacher-ng stop
/bin/rm -rf /var/cache/apt-cacher-ng/$BACKEND
/etc/init.d/apt-cacher-ng start

ENDSSH
  done
}
#}}}

# Option needs yes or no {{{
function need_yes_or_no () {

  OPT_VALUE="$1"
  OPT_NAME="$2"

  if [ $(echo ${OPT_VALUE} | grep -Ec "(yes|no)") -ne 1 ]
  then
    echo -e "\n${blue}${OPT_NAME} must be one of yes or no, exiting.${norm}\n"
    exit 0
  else
    echo ${OPT_VALUE}
  fi

}
#}}}

# Main function {{{
function do_main () {

 push_reprepro
 [ "${CLEANUP_APT_CACHER}" == "yes" ] && ssh_rmcache 

}
#}}}

# Usage {{{
function usage () {
cat << EOF

Ce srcipt permet le cleanup du cache apt sur le serveur distant

OPTIONS :
  -b  build package <yes|no> yes or no
      else cleanup reprepro and dupload existing package
  -c  cleanup apt-cacher servers <yes|no>
  -e  environment <prod|preprod|dev>
  -i  print info, what will be done
  -u  make package update reprepro
  -l  Liste des serveurs apt-cacher-ng disponibles
  -m  Update Easter-eggs repo mirror on pkg-01.logicmax.pw <yes|no>
  -t  cleanup tattoo apt-cacher
  -h  this help

EOF

exit 0
}
#}}}

# Print info {{{
function print_info () {

cat << EOF

EOF

[ "${BUILD_PACKAGE}" == "yes" ] && cat << EOF

rm -f ../${PKG}_${VERS}*
dpkg-buildpackage

EOF

cat << EOF

ssh ${REPREPRO_CONNECTION}
cd $REPREPRO_DIR
reprepro -V remove $REPRERPO_DIST ${PKG}
reprepro -V dumpunreferenced

dupload --force --to $DUPLOAD_DIST ../${PKG}_${VERS}_amd64.changes

ssh ${MIRROR_REPREPRO_CONNECTION}
cd ${EE_REPREPRO_MIRROR}
reprepro -V remove stretch-ee ee-intaller-libs
reprepro -V deleteunreferenced

/usr/local/bin/updatemirror.sh ${EE_REPREPRO_MIRROR}
EOF

if [ "${CLEANUP_APT_CACHER}" == "yes" ]
then
  for connection in "${SRV_LIST[@]}"
  do
    cat << EOF

${connection/*: /}

export TERM=LINUX
sudo -i bash -s

/etc/init.d/apt-cacher-ng stop
/bin/rm -rf /var/cache/apt-cacher-ng/${BACKEND}
/etc/init.d/apt-cacher-ng start

EOF
  done
fi

exit 0
}
#}}}

# Command line options {{{

[ $# -eq 0 ] && echo -e "\nIl manque une option\n" && usage

while getopts ":b:c:e:iuhlm:t" OPTION
do
  case $OPTION in
    b)
      BUILD_PACKAGE=$(need_yes_or_no ${OPTARG} BUILD_PACKAGE)
      ;;
    c)
      CLEANUP_APT_CACHER=$(need_yes_or_no ${OPTARG} CLEANUP_APT_CACHER)
      ;;
    e)
      if [ $(echo ${OPTARG} | grep -Ec "(prod|preprod|dev)") -ne 1 ]
      then
        echo -e "\n${blue}ENV must be one of prod, preprod, dev, exiting.${norm}\n"
        exit 0
      else
        ENV=$( set_env ${OPTARG})
        set_env ${OPTARG}
      fi
      ;;
    u)
      DO="MAIN"
      ;;
    l)
      echo -e "\nConnections available:"
      get_list
      exit 0
      ;;
    m)
      UPDATE_MIRROR=$(need_yes_or_no ${OPTARG} UPDATE_MIRROR)
      ;;
    i)
      DO="INFO"
      ;;
    h)
      usage
      ;;
    t)
      SRV_LIST+=("${SRV_TATTOO}")
      SRV_LIST_QTT=${#SRV_LIST[*]}
      SRV_LIST_END=$((SRV_LIST_QTT-1))
      ;;
  esac
done
#}}}

# Check if var is defined {{{
if [[ ! -v BUILD_PACKAGE ]]
then
  echo -e "\n${blue}You must say if you build package or not.${norm}"
  usage
fi
if [[ ! -v CLEANUP_APT_CACHER ]]
then
  echo -e "\n${blue}You must say if you cleanup apt-cacher or not.${norm}"
  usage
fi
if [[ ! -v UPDATE_MIRROR ]]
then
  echo -e "\n${blue}You must say if you update Ee repo mirror or not.${norm}"
  usage
fi
if [[ ! -v ENV ]]
then
  echo -e "\n${blue}You must define on which reprepro environment you'll dupload on.${norm}"
  usage
fi
if [[ ! -v DO ]]
then
  echo -e "\n${blue}One of option -u (update) or -i (get information) must be use.${norm}"
  usage
fi
#}}}

# Check if var value {{{
if [ -z "${BUILD_PACKAGE}" ]
then
  echo "BUILD_PACKAGE not defined, exiting"
  exit 0
fi

if [ ! -z "${ENV}" ]
then
  case ${DO} in
    MAIN)
      do_main
      ;;
    INFO)
      print_info
      ;;
    *)
      echo "${blue}Need an action to do, one of update (-u) or info (-i), exiting${norm}"
      exit 0
      ;;
  esac
else
  echo "${blue}ENV not defined, exiting.${norm}"
  exit 0
fi
#}}}

# vim:expandtab:shiftwidth=2:softtabstop=2:tabstop=2:noexpandtab:foldmethod=marker:foldlevel=0

