#!/usr/bin/bash
# Copyright 2018 Chad Lemmen http://www.lemmen.com
#
# This file is part of Pilot Log.
#
# Pilot Log is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# Pilot Log is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pilot Log. If not, see <https://www.gnu.org/licenses/>.
###############################################################################
#
# Upgrade script
# To upgrade an existing installation, you can download the latest version from
# http://pilotlog.stansoft.org. Before installing the upgrade make sure you
# have a good backup. All of your data is stored in
# $HOME/.local/share/pilotlog/data.

# Extract the downloaded archive into your pilotlog directory which will
# overwrite your existing programs, but will keep your database.
# Run the following command:
# tar -xvf pilotlog-vX-x86_64.tar.bz2 -C /path-to-pilotlog

ssdir=$(dirname $(realpath $BASH_SOURCE))
# Set the environment
. $ssdir/etc/pilotlog.sh
sql=psql
dbname=pilotlog

"$ssdir"/pgsql/bin/pg_ctl status
if [ $? -eq 3 ]; then
  # Server is not running, start it...
  # setsid - run a program in a new session otherwise it exits with this script
  setsid "$ssdir"/pgsql/bin/pg_ctl -D "$PGDATA" -l "$PGDATA"/pglog start

  # Make sure the database server is up
  for i in {1..5}; do
    sleep 2
    "$ssdir"/pgsql/bin/pg_ctl status && break
    echo "Attempt $i of 5"
    if [ "$i" -eq 5 ]; then
      echo "Failed to start the database, see $PGDATA/pglog for details"
      echo "If the problem is the port number, change PGPORT"
      echo "in $ssdir/etc/pilotlog.sh"
      exit
    fi
  done
fi

"$sql" "$dbname" <<- SQL 
-- v4
create table log_field
  (
    field_id char(7),
    descr char(20)
  );

alter table log_entry add column custom1 numeric(7,1),
                      add column custom2 numeric(7,1),
                      add column custom3 numeric(7,1),
                      add column custom4 numeric(7,1),
                      add column custom5 numeric(7,1),
                      add column custom6 numeric(7,1);
create table prt_parm
  (
    rpt_name char(15),
    username char(10),
    lp_name char(15),
    copies smallint,
    paper_tray smallint
  );

SQL
