#!/bin/bash

. /usr/share/dosis2/bin/shell-support-functions

OS="`getos`"

if [[ "$1" = "-h" ]]; then
    echo "Use like:"
    echo "    ./changetz.bash <timezone>"
    echo 
    echo "<timezone>:"
    echo "    America/Los_Angeles" 
    echo "    America/Denver"
    echo "    America/Phoenix"
    echo "    America/Chicago"
    echo "    America/New_York"
    echo "    Pacific/Honolulu"
    echo "    America/Juneau"
    echo "    Europe/London"
    echo "    Europe/Paris"
    exit 0
fi

if [ -z "$1" ]; then
    echo "No Timezone supplied on command line. Will do nothing."
else    
    if [ "${OS}" = "CentOS" ]; then
        echo "ZONE=\"$1\"" > /etc/sysconfig/clock

        /usr/sbin/tzdata-update
        /sbin/hwclock --systohc --utc

        target="/var/lib/pgsql/9.2/data/postgresql.conf"
        sed -i -e "s/^(#)?timezone =.*/timezone =/g" $target

        tz=$1
        tz=${tz/\//\\/}
        tz=${tz/\ /_}

        name="timezone ="
        pair="timezone =\'$tz\'"
        target="/var/lib/pgsql/9.2/data/postgresql.conf"
        sed -i.swp  -e  "\|$name.*|h; \${x;s/$name.*//;{g;t okr};a\\" -e "$pair" -e  "}; :okr //s/$name.*/$pair/ " $target

        su - postgres -c "psql -d dosis2  -c 'SELECT pg_reload_conf()'"
    elif [ "${OS}" = "Ubuntu" ]; then
        ln -sfT "/usr/share/zoneinfo/$1" "/etc/localtime"
        /sbin/hwclock --systohc --utc

        echo "timezone = '$1'" > "/opt/dosis2/etc/postgresql/10/conf.d/90-timezone.conf"
        echo "$1" > /etc/timezone
        
        su - postgres -c "psql -d dosis2 -c 'SELECT pg_reload_conf()'"
    else
        abort 2 "Unsupported OS: ${OS}"
    fi
fi
