#!/bin/sh
#----------
# Copyright 2018 Kai Thoene. All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without modification, are
# permitted provided that the following conditions are met:
# 
#    1. Redistributions of source code must retain the above copyright notice, this list of
#       conditions and the following disclaimer.
# 
#    2. Redistributions in binary form must reproduce the above copyright notice, this list
#       of conditions and the following disclaimer in the documentation and/or other materials
#       provided with the distribution.
# 
# THIS SOFTWARE IS PROVIDED BY KAI THOENE ''AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KAI THOENE OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 
# The views and conclusions contained in the software and documentation are those of the
# authors and should not be interpreted as representing official policies, either expressed
# or implied, of Kai Thoene.
#----------
#----------
# Check restart of this script.
[ "$1" = "-" ] && { SUDORESTART=yes; shift; }
#----------
# Check distribution.
type apk >/dev/null 2>&1 || { echo "Not Alpine Linux! 'apk' missing!" >&2; exit 1; }
[ -r /etc/os-release ] || { echo "Not Alpine Linux! '/etc/os-release' missing!" >&2; exit 1; }
OSVERSION=`sed -e '/^VERSION_ID=/p' -e d /etc/os-release | cut -d= -f2` || { echo "Not Alpine Linux! Cannot find version" >&2; exit 1; }
[ -z "$OSVERSION" ] && { echo "Not Alpine Linux! Cannot get version!" >&2; exit 1; }
#----------
# Check root
unset MEUID
MEUID=`id -u`
[ "$MEUID" != 0 ] && {
  [ "$SUDORESTART" = "yes" ] && { echo "Must run this script as root!" >&2; exit 1; }
  if type sudo >/dev/null 2>&1; then echo "You don't have super cow powers! Try to start with sudo ..." >&2; sudo "$SHELL" "$0" - $@; exit $?; else echo "Must run this script as root! Missing tool! TOOL=sudo" >&2; exit 1; fi
}
#
#----------
# Script functions.
#
getyesorno() {
  # Returns 0 for YES. Returns 1 for NO.
  # Returns 2 for abort.
  DEFAULT_ANSWER="$1"
  USER_PROMPT="$2"
  #--
  unset OK_FLAG
  while [ -z "$OK_FLAG" ]; do
    read -r -p "QUESTION -- $USER_PROMPT" -n 1 YNANSWER
    [ $? -ne 0 ] && return 2
    if [ -z "$YNANSWER" ]; then
      YNANSWER="$DEFAULT_ANSWER"
    else
      echo
    fi
    case "$YNANSWER" in
      [yY])
        YNANSWER=Y
        return 0
        ;;
      [nN])
        YNANSWER=N
        return 1
        ;;
    esac
  done
}  # getyesorno
#
#----------
# Read command options.
#
CMD="$1"
#
#----------
# Update repositories.
# Upgrade software.
#
[ -z "$CMD" ] && {  # Normal installation. / No options.
  apk update
  apk upgrade
  apk add wget wget-doc
  #
  #----------
  # Perl releated.
  #
  apk add unzip unzip-doc perl perl-doc perl-utils perl-test-taint perl-test-taint-doc perl-netaddr-ip perl-netaddr-ip-doc perl-net-ip perl-net-ip-doc perl-yaml perl-yaml-doc perl-log-log4perl perl-log-log4perl-doc
  cpan Data::Validate::IP
  #
  #----------
  # Download and install ddclient.
  #
  at_exit() { [ -d "$TMPDIR" ] && rm -rf "$TMPDIR"; }
  URI="https://sourceforge.net/projects/ddclient/files/latest/download"
  TMPDIR=`mktemp -p . -d` && trap at_exit EXIT HUP INT QUIT TERM
  (
    DISTFILE="ddclient.zip"
    cd "$TMPDIR"
    if wget -o log -q "$URI" -O "$DISTFILE"; then
      unzip -q "$DISTFILE" || { echo "ERROR -- unzip!" >&2; exit 1; }
      unset DIR
      while IFS= read _LINE; do
        [ -d "$_LINE" ] && { DIR="$_LINE"; break; }
      done <<EOF
`ls -1`
EOF
      [ -n "$DIR" ] || { echo "ERROR -- Find extracted directory!" >&2; exit 1; }
      PRG=ddclient
      if [ -r "$DIR/$PRG" ]; then
        install -v -o root -g root -m "u=rwx,go=rx" "$DIR/$PRG" "/usr/bin/$PRG"
        install -v -o root -g root -m "u=rwx,go=" -d /etc/ddclient /var/cache/ddclient
      else
        echo "ERROR -- Cannot find program! PRG=$PRG" >&2
        exit 1
      fi
    else
      echo "ERROR -- Cannot download distribution file! DISTFILE=$DISTFILE" >&2
      exit 1
    fi
  )
  #
  #----------
  # Optional: Install existing ddclient.conf / But don't overwrite!
  #
  [ -f /etc/ddclient/ddclient.conf ] || [ -r ddclient.conf ] && { install -v -o root -g root -m "u=rwx,go=" ddclient.conf /etc/ddclient; }
  #
}
#
[ "$CMD" = "--service-only" -o -z "$CMD" ] && {
  #
  #----------
  # Optional: Install service.
  #
  echo "INFO -- Install rc file."
  RCFILE="/etc/init.d/ddclient"
  [ -f "$RCFILE" ] && getyesorno N "Overwrite '$RCFILE'? [yN]" && rm "$RCFILE"
  [ -f "$RCFILE" ] || {
    cat > "$RCFILE" <<'EOF'
#!/sbin/openrc-run
description="DDclient - Update accounts for Dynamic DNS Service Provider."
pidfile=/var/run/ddclient.pid
command="/usr/bin/ddclient"
command_args="-pid '$pidfile'"
depend() { use net dns logger; }
EOF
    chown root:root "$RCFILE"
    chmod u=rwx,go=rx "$RCFILE"
    echo "INFO -- rc file installed, but not activated by this script. RCFILE=$RCFILE"
    echo "INFO -- Activate it by..: rc-update add ddclient"
    echo "INFO -- Deactivate it by: rc-update del ddclient"
  }
  #
}
#
echo "OK -- ddclient ready!"
exit 0
