#!/system/bin/sh
#
# restore a drd-conf.img

BASE="$(basename $0)"

TMPDIR="/data/local"
export TMPDIR
CONFIG_DIR="/drd-conf"

check() {
  tmpmount=$(mktemp -d)
  if [ $? -ne 0 ] ; then
    echo "mktemp call while checking failed"
    exit 2
  fi
  mount -o loop,ro -t ext4 "$1" "${tmpmount}"
  if [ $? -ne 0 ]; then
    echo "$1 does not look like a .img file"
    rmdir "${tmpmount}"
    exit 3
  fi
  umount "${tmpmount}"
  rmdir "${tmpmount}"
}

clean() {
  echo -n "cleaning ${CONFIG_DIR} directory... "
  # always preserve config file
  rm -rf "${CONFIG_DIR}"/*
  echo "done"
}

restore() {
  echo "restoring ${CONFIG_DIR} from $1... "
  # create tmpdir and mount new drd-conf.img
  tmpmount=$(mktemp -d)
  if [ $? -ne 0 ] ; then
    echo "mktemp call while restoring failed"
    exit 4
  fi
  mount -o loop,ro -t ext4 "$1" "${tmpmount}"
  if [ $? -ne 0 ]; then
    echo "$1 does not look like a .img file"
    rmdir "${tmpmount}"
    exit 5
  fi
  # copy files
  cp -a "${tmpmount}"/* ${CONFIG_DIR}/
  # clean up
  umount "${tmpmount}"
  rmdir "${tmpmount}"
  echo "restarting services..."
  drd-services --restart mosquitto
  drd-services --restart dropbear
  echo "done"
}


HELP="${BASE} [-c] drd-conf.img
    -c --clean clean ${CONFIG_DIR} directory
"

ARGS=`getopt -o "c" -l "clean" -n "${BASE}" -- "$@"`
if [ $? -ne 0 ] ; then
  echo "${HELP}"
  exit 1
fi

eval set -- "$ARGS"

DO_CLEAN=0

while true
do
    case "$1" in
        -c|--clean)
            DO_CLEAN=1
            shift
            ;;
        --)
            shift
            break
            ;;
        *)
            break
            ;;
    esac
done

if [ $# -lt 1 ] ; then
    echo "${HELP}"
    exit 0
fi

if [ "$1"x = ""x ] ; then
    echo "${HELP}"
    exit 1
fi

check $1

if [ $DO_CLEAN -eq 1 ] ; then
    clean
fi

restore $1
sync
exit 0
