#!/bin/sh

PREFIX=/usr
: ${LIBDIR=$PREFIX/lib}
. "$LIBDIR/libalpine.sh"

zroot="$ROOT"usr/share/zoneinfo

usage() {
  cat <<-__EOF__
		usage: setup-timezone [-h] [-k|-i] [TIMEZONE]

		Sets the timezone for the system.

		options:
		 -h  Show this help
		 -i  Install tzdata and symlink instead of making a copy
		 -k  Keep previous copies of tzdata

		TIMEZONE is relative $zroot.

		If TIMEZONE is not specified user will be prompted.
	__EOF__
  exit $1
}

show_tz_list() {
  local i z= list=
  local path="$zroot/$1"
  [ -d "$path" ] || return 1

  for i in $(find $path/ -maxdepth 1); do
    case $i in
    *.tab|*/) continue;;
    esac
    if [ -d "$i" ]; then
      z="$z ${i##*/}/"
    else
      z="$z ${i##*/}"
    fi
  done
  ( cd_assert $path && ls --color=never -Cd $z )
}

setup_tz() {
  local zonepath="$1"
  local zone="${zonepath#*/zoneinfo/}"
  if ! $INSTALL_TZDATA; then
    local zdir="${zonepath%/*}"/
    zdir="${zdir#*/zoneinfo/}"
    if ! $KEEP_TZDATA; then
      rm -rf "${ROOT}"etc/zoneinfo
    fi
    mkdir -p "${ROOT}"etc/zoneinfo/$zdir
    cp "$zonepath" "${ROOT}"etc/zoneinfo/$zdir/
    zonepath=/etc/zoneinfo/$zone
  fi
  rm -f "${ROOT}"etc/localtime
  ln -s "$zonepath" "${ROOT}"etc/localtime
  printf "%s\n" "$zone" > "${ROOT}"etc/timezone 2>/dev/null || true
  if [ -z "$ROOT" ] || [ "$ROOT" = "/" ]; then
    rm -f /tmp/sxmo_conky_time_state
    if pidof -s Xorg >/dev/null 2>&1; then
      su -s /bin/sh user -c '
        export PATH="/home/user/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin"
        export DISPLAY=:0
        export XDG_RUNTIME_DIR="/run/user/10000"
        export XDG_CONFIG_HOME="/home/user/.config"
        sxmo_hook_statusbar.sh time >/dev/null 2>&1 || {
          pkill -9 -x conky >/dev/null 2>&1 || true
          DISPLAY=:0 CONKY_DPY=:0 conky -c /home/user/.config/sxmo/conky.conf -d >/dev/null 2>&1 </dev/null || true
        }
      ' >/dev/null 2>&1 || true
    fi
  fi
}

INSTALL_TZDATA=false
KEEP_TZDATA=false
while getopts "hikz:" opt; do
  case $opt in
    h) usage 0;;
    i) INSTALL_TZDATA=true;;
    k) KEEP_TZDATA=true;;
    z) ZONE="$OPTARG";;  # backwards compat
    '?') usage "1" >&2;;
  esac
done
shift $(( $OPTIND - 1))

if [ -z "$ZONE" ]; then
  ZONE="$1"
fi

if [ "$ZONE" = "none" ]; then
  exit 0
fi

need_apk=true
if [ -d "$zroot" ]; then
  if [ -n "$ZONE" ] && [ -f "$zroot/$ZONE" ]; then
    need_apk=false
  elif [ -z "$ZONE" ] && [ -f "$zroot/UTC" ]; then
    need_apk=false
  fi
fi

if $need_apk; then
  if $INSTALL_TZDATA; then
    pkg=tzdata
    apkdel=
  else
    pkg="--force --virtual .setup-timezone tzdata"
    apkdel=".setup-timezone"
  fi

  apk add --no-progress --quiet $pkg || die "Failed to install tzdata package"

  if [ -n "$apkdel" ]; then
    trap "exit 1" INT TERM HUP
    trap "apk del --no-progress --quiet $apkdel" EXIT
  fi
fi

if [ -L "${ROOT}"etc/localtime ]; then
  default_timezone=$(readlink "${ROOT}"etc/localtime)
  default_timezone=${default_timezone#*/zoneinfo/}
else
  default_timezone=UTC
fi

if [ -n "$ZONE" ]; then
  [ -f "$zroot/$ZONE" ] || die "'$ZONE' is not a valid timezone on this system"
  setup_tz "$zroot"/"$ZONE"
else
  while true; do
    show_tz_list
    echo ""
    ask "Which timezone are you in? (or '?' or 'none')" "$default_timezone"
    timezone=$(printf %s "$resp" | sed 's/\/\+/\//g; s/\/$//')
    case "$timezone" in
      none|abort) break;;
      ""|"?") continue;;
    esac

    while [ -d "$zroot/$timezone" ]; do
      show_tz_list "$timezone"
      echo ""
      ask "What sub-timezone of '$timezone' are you in? (or '?')"
      zone=$(printf %s "$resp" | sed 's/\/\+/\//g; s/\/$//')
      case "$zone" in
        ""|"?") continue;;
      esac
      default_timezone="$timezone"
      timezone="$timezone/$zone"
    done

    if [ -f "$zroot/$timezone" ]; then
      setup_tz "$zroot/$timezone"
      break
    fi
    echo "'$timezone' is not a valid timezone on this system"
  done
fi
