#!/bin/bash
#postinst script for airtime

set -x

. /usr/share/debconf/confmodule

wwwdir="/usr/share/airtime"
tmpdir="/var/lib/airtime/tmp"
configdir="/etc/airtime"
includefile="${configdir}/apache.conf"
a2tplfile="${configdir}/apache.vhost.tpl"
phpinifile="${configdir}/airtime.ini"
OLDVERSION="$2"
NEWVERSION="2.2.0"

case "$1" in
  configure|reconfigure)

    webserver="apache2"
    php="php5"

    #  clean up previous configurations
    if [ -L /etc/$webserver/conf.d/airtime.conf ]; then
      rm -f /etc/$webserver/conf.d/airtime.conf
    fi

    if [ -f /etc/$webserver/sites-available/airtime-vhost ]; then
      a2dissite airtime-vhost
    fi

    # this file in 1.8.2 is a directory path in 1.9.3
    if [ -f /var/www/airtime/utils/airtime-import ]; then
      rm -f /var/www/airtime/utils/airtime-import
    fi

    # APACHE config
    echo "Setting up apache2..."

    # create the document root if it doesn't exist
    if [ ! -d $wwwdir/public/ ]; then
      install -d -m755 $wwwdir/public/
    fi

    # set up the virtual host
    db_get airtime/apache-setup
    if [ "$RET" == "system-wide (all vhosts)" ]; then
      if [ ! -d /etc/$webserver/conf.d/ ]; then
        install -d -m755 /etc/$webserver/conf.d/
      fi
      if [ ! -e /etc/$webserver/conf.d/airtime.conf ]; then
        ln -s ${includefile} /etc/$webserver/conf.d/airtime.conf
      fi

    elif [ "$RET" == "dedicated v-host" ]; then
      db_get airtime/apache-servername
      SN=$RET
      db_get airtime/apache-serveradmin
      SA=$RET

      if [ ! -d /etc/$webserver/sites-available/ ]; then
        install -d -m755 /etc/$webserver/sites-available/
      fi
      sed -e "s/__SERVER_ADMIN__/${SA}/;s/__SERVER_NAME__/${SN}/" \
        ${a2tplfile} > /etc/$webserver/sites-available/airtime-vhost

      command -v a2ensite > /dev/null
      RETVAL=$?
      if [ $RETVAL -eq 0 ]; then
      a2ensite airtime-vhost
      fi
    fi

    # enable the rewrite module
    command -v a2enmod > /dev/null
    RETVAL=$?
    if [ $RETVAL -eq 0 ]; then
      a2enmod rewrite
    fi

    # remove the default site, if requested to
    db_get airtime/apache-deldefault
    if [ "$RET" == "remove default" ]; then
      if [ -f /etc/apache2/sites-available/default ]; then
      a2dissite default
      fi
    fi

    # PHP config
    echo "Configuring php5..."
    if [ ! -d /etc/$php/conf.d/ ]; then
      install -d -m755 /etc/$php/conf.d/
    fi
    if [ ! -e /etc/$php/conf.d/airtime.ini ]; then
      ln -s ${phpinifile} /etc/$php/conf.d/airtime.ini
    fi

    # XXX ICECAST XXX
    db_get airtime/icecast-setup
    if [ "$RET" == "true" ]; then
      if [ -f /etc/default/icecast2 -a -f /etc/icecast2/icecast.xml ]; then
        echo "Setting up icecast2..."
        sed -i "s:ENABLE=.*:ENABLE=true:g" /etc/default/icecast2
        db_get airtime/icecast-sourcepw
        ICESOURCE=$RET
        sed -i "s:<source-password>.*<\/source-password>:<source-password>$ICESOURCE<\/source-password>:g" /etc/icecast2/icecast.xml
        db_get airtime/icecast-relaypw
        ICERELAY=$RET
        sed -i "s:<relay-password>.*<\/relay-password>:<relay-password>$ICERELAY<\/relay-password>:g" /etc/icecast2/icecast.xml
        db_get airtime/icecast-adminpw
        ICEADMIN=$RET
        sed -i "s:<admin-password>.*<\/admin-password>:<admin-password>$ICEADMIN<\/admin-password>:g" /etc/icecast2/icecast.xml
        db_get airtime/icecast-hostname
        ICEHOST=$RET
        sed -i "s:<hostname>.*<\/hostname>:<hostname>$ICEHOST<\/hostname>:g" /etc/icecast2/icecast.xml

        # restart icecast server
        invoke-rc.d icecast2 restart || true

          # save icecast hostname and source-password in airtime
          db_get airtime/icecast-hostname
          ICEHOST=$RET
          sed -i "s:'s1_host', '127.0.0.1', 'string':'s1_host', '$ICEHOST', 'string':g" ${tmpdir}/airtime_mvc/build/sql/defaultdata.sql

          db_get airtime/icecast-sourcepw
          ICESOURCE=$RET
          sed -i "s:'s1_pass', 'hackme', 'string':'s1_pass', '$ICESOURCE', 'string':g" ${tmpdir}/airtime_mvc/build/sql/defaultdata.sql

      else
        echo "The icecast2 package does not appear to be installed on this server."
      fi
    fi

    # Monit setup
      if [ -f /etc/default/monit ]; then
        echo "Setting up monit configuration..."
         sed -i 's:startup=.*:startup=1:g' /etc/default/monit

           MONITCONFIGURED=$(grep "include /etc/monit/conf.d" /etc/monit/monitrc || true)
           if [ -z "$MONITCONFIGURED" ]; then
            echo "include /etc/monit/conf.d/*" >> /etc/monit/monitrc
           fi

            invoke-rc.d monit restart
      else
        echo "The monit package does not appear to be installed on this server."
      fi

     # get airtime admin password on new installs
	if [ ! -e /var/log/airtime/pypo/pypo.log ]; then
     		db_get airtime/admin-password
     		AIRTIMEADMIN=$RET
     		sed -i "1s:md5('admin'):md5('$AIRTIMEADMIN'):g" ${tmpdir}/airtime_mvc/build/sql/defaultdata.sql
	fi

    # get the main storage directory specified by the user
    db_get airtime/storage-directory
     AIRTIMESTORAGE=$RET
      if [ "$AIRTIMESTORAGE" != "/srv/airtime/stor/" ]; then
       sed -i "1s:/srv/airtime/stor/:$AIRTIMESTORAGE:g" ${tmpdir}/install_minimal/include/airtime-install.ini
      fi

    # stop debconf so daemons started by the install script cannot hold open the pipe
    db_stop

    # start rabbitmq if it isn't running
    if [ -f /etc/init.d/rabbitmq-server ]; then
      RABBITMQSTOPPED=$(invoke-rc.d rabbitmq-server status | grep no_nodes_running || true)
        if [ -n "$RABBITMQSTOPPED" ]; then
           invoke-rc.d rabbitmq-server start
        fi

        # Warn if rabbitmq is installed but not set to start on boot
        RABBITMQSTARTONBOOT=$(ls /etc/rc2.d/ | grep rabbitmq || true)
          if [ -z "$RABBITMQSTARTONBOOT" ]; then
            echo "Warning: rabbitmq-server is not configured to start after a reboot!"
            echo "Fix Default-Start and Default-Stop lines in /etc/init.d/rabbitmq-server"
            echo "then run this command as root: update-rc.d rabbitmq-server defaults"
          fi
    else
     echo "The rabbitmq-server package does not appear to be installed on this server."
    fi

    # restart apache
    invoke-rc.d apache2 restart

    # fix the Liquidsoap symlink if it doesn't point to standard location
    if [ -h /usr/bin/airtime-liquidsoap ]; then
      SYMLINK_TARGET=`readlink /usr/bin/airtime-liquidsoap`
       if [ "$SYMLINK_TARGET" != "/usr/bin/liquidsoap" ]; then
        echo "Liquidsoap symlink points to the wrong place, fixing it!"
         rm /usr/bin/airtime-liquidsoap
          ln -s /usr/bin/liquidsoap /usr/bin/airtime-liquidsoap
       fi

       if [ "$SYMLINK_TARGET" == "/usr/bin/liquidsoap" ]; then
        echo "Liquidsoap symlink points to the right place!"
       fi
    fi

    # symlink the Liquidsoap path to standard location, if symlink doesn't exist
    if [ ! -h /usr/bin/airtime-liquidsoap ]; then
     echo "Creating symlink for Liquidsoap..."
      ln -s /usr/bin/liquidsoap /usr/bin/airtime-liquidsoap
    fi

    # don't run airtime-install if the user is doing a dpkg-reconfigure
    if [ "$1" = "reconfigure" ] || [ -n "$DEBCONF_RECONFIGURE" ] ; then
      echo "Reconfiguration complete."
    else

      if [ -n "$OLDVERSION" ] && [[ "${OLDVERSION:0:3}" < "1.9" ]]; then
        echo "Upgrades from Airtime versions before 1.9.0 are not supported. Please back up your files and perform a clean install."
      else

        mkdir -p /var/log/airtime
        cd $tmpdir/install_minimal/

        if [ "${OLDVERSION:0:5}" == "${NEWVERSION}" ] ; then
          echo "Reinstallation detected..."
          echo | ./airtime-install --disable-deb-check -rp 2> /var/log/airtime/reinstallation-errors.log
        else

          ./airtime-install --disable-deb-check 2> /var/log/airtime/installation-errors.log

        fi

          # Update the desktop menu to show Airtime
          if test -x /usr/bin/update-menus; then
            update-menus;
          fi
      fi
    fi
  ;;

  abort-upgrade|abort-remove|abort-deconfigure)

  ;;

  *)
       echo "postinst called with unknown argument \`$1'" >&2
       exit 1
  ;;
esac

#DEBHELPER#

exit 0