#!/bin/bash

function InitProfile()
{
  InitFonts
  SetupWine         || return 1
  SetupWineTweaks   || return 1
  SetupEnv          || return 1
  InitLocalSettings || return 1

  echo "ok (profile)"
}

function InitFonts()
{
  # check if we are not installed
  isInstalledTV && return 0

  # apply workaround for fontconfig 2.10+ (attribute prefix="xdg")
  # (force fontconfig dir to be created inside the profile dir, not adjacent to it)
  if isQuickSupport; then
    export FONTCONFIG_FILE="$TV_SCRIPT_DIR/fonts_quick.conf"
  elif [ -e '/etc/fonts/fonts.conf' ]; then
    export FONTCONFIG_FILE="$TV_SCRIPT_DIR/fonts_portable.conf"
  fi

  [ -n "$FONTCONFIG_FILE" ] && echo "FONTCONFIG_FILE: $FONTCONFIG_FILE"
  true
}

function SetupWine()
{
  # setup dosdevices and symlinks
  local c_sym="$WINEPREFIX/dosdevices/c:"
  local c_dir="$WINEPREFIX/drive_c/"
  local z_sym="$WINEPREFIX/dosdevices/z:"
  local z_dir="/"

  make_path "$WINEPREFIX/dosdevices"	&&
  setup_drive_symlink "$c_sym" "$c_dir"	&&
  setup_drive_symlink "$z_sym" "$z_dir"	&&

  # setup program files and logfile symlinks
  setup_prog_dir			&&
  setup_temp_dir			&&
  setup_winemenubuilder

  echo 'SetupWine: ok'
}


# setup/validate drive symlinks
function setup_drive_symlink()
{
  local sym="$1"
  local dst="$2"

  if ! ( [ -h "$sym" ] && [ -d "$sym" ] ) ; then	# symlink to dir
    rm -f "$sym"
  fi
  [ -d "$sym" ] || ln -s "$dst" "$sym" || fail "Could not create $sym (link to $dst)"
}

# setup temp dir
function setup_temp_dir
{
  local cuser=$(id -un)
  local basepath="$WINEPREFIX/drive_c/users/$cuser"

  mkdir -p "$basepath/temp" || die 'setup_temp_dir failed'
}

function setup_prog_dir()
{
  local progdir="$WINEPREFIX/drive_c/TeamViewer"
  local progsrc="$TV_WINE_DIR/drive_c/TeamViewer"
  local name
  local dst

  if ! [ -d "$progdir" ] ; then
    mkdir -p "$progdir" || fail "Could not create $progdir"
  fi

  # always check all files (may change due to updates)
  for item in "$progsrc"/* ; do
    name=${item##/*/}		# aka basename
    dst="$progdir/$name"

    if ! ( [ -h "$dst" ] && [ -f "$dst" ] ) ; then	# symlink to file
      rm -f "$dst"
      ln -s "$item" "$dst" || die "Could not create $dst (link to $item)"
    fi
  done
}

function setup_winemenubuilder()
{
  local sysdir="$WINEPREFIX/drive_c/windows/system32"
  local syssrc="$TV_WINE_DIR/drive_c/windows/system32"

  mkdir -p "$sysdir"
  cp "$syssrc/winemenubuilder.exe" "$sysdir/winemenubuilder.exe"
  [ -e "$sysdir/winemenubuilder.exe" ] || die "Could not copy winemenubuilder"
}

function SetupWineTweaks()
{
  [ "$USE_LOCAL_WINE" = 'yes' ] && return
  [ -d "$WINEPREFIX/.tweak"   ] || mkdir "$WINEPREFIX/.tweak"

  local tweakdir="$TV_SCRIPT_DIR"
  OverrideTweakDir

  RequireWineServer		# make sure wineserver is running (QS)

  winetweak fontsmooth_rgb	# Enable Subpixel Hinting
  winetweak no_xvidmodeext	# Disable XVidExtension (causes problems with some drivers)
  winetweak no_xrandr		# Disable XRandR (causes problems with some drivers)
  winetweak no_fileassocs	# Disable synchronizing of file associations and menu entries
#  winetweak setwinver		# Set Win2k mode for TeamViewer

  if [ "$tweakdir" != "$TV_SCRIPT_DIR" ]; then
    rm "$tweakdir"
    true # don't fail here
  fi
}

# LIN-1078
function OverrideTweakDir()
{
  [ -n "$tweakdir" ] || die 'internal error'

  isStrAscii "$tweakdir" && return

  local override="/tmp/tv$$_$RANDOM_tweak"
  ln -s "$tweakdir" "$override" || die "OverrideTweakDir failed"

  tweakdir="$override"
}

function winetweak()
{
  local tweak="$1"
  local tweakmark="$WINEPREFIX/.tweak/$tweak"
  local tweakfile="$tweakdir/$tweak.reg"

  [ -e "$tweakmark" ] && return

  wine regedit "$tweakfile" && touch "$tweakmark" || die "winetweak $tweakmark failed"
}

function SetupEnv()
{
  make_path        "$TV_CFG_DIR" 0700	|| die 'SetupEnv failed'

  SetupEnvTAR
}

function SetupEnvTAR()
{
  isInstalledTV && return					# only for TAR_NI / QS / CQS

  local dtdst="$TV_BASE_DIR/teamviewer.desktop"
  local dtsrc="$TV_DESKTOP_DIR/teamviewer.desktop.template"
  local ticon="$TV_DESKTOP_DIR/teamviewer.png"
  local texec="$TV_SCRIPT_DIR/teamviewer"

  [ -e "$dtdst" ] && grep -q "$texec" "$dtdst" && return	# already exists, proper path

  # Create desktop shortcut
  sed -e "s|EXEC|$texec|g" \
      -e "s|ICON|$ticon|g" \
      "$dtsrc" > "$dtdst"
}

function InitGlobalSettings()
{
  ImportTV10Settings && return
  ImportTV9Settings  && return
  true
}

function InitLocalSettings()
{
  # check if we are installed
  isInstalledTV || return 0

  [[ "$TV_VERSION" = 12* ]] && die 'internal error' # must be updated

  ImportTV10SettingsClient   && return
  ImportTV9Settings 'client' && return
  true

#  ImportDefaults	# this functionality has been removed. Put defaults in global.conf DefaultSettings\...
}

function ImportTV9Settings()
{
  local conftype="$1"
  local globalConf="$TV_BASE_DIR/config/global.conf"
  local clientConf="$TV_CFG_DIR/client.conf"
  local globalConfOld='/opt/teamviewer9/config/global.conf'
  local copy='n'
  local oldpath
  local newpath

  grep -q '9.0.32150' "$globalConfOld" 2>/dev/null && copy='y'

  if [ "$conftype" = 'client' ]; then
    newpath="$clientConf"
    oldpath="${newpath/teamviewer/teamviewer9}"
  else
    newpath="$globalConf"
    oldpath="$globalConfOld"
  fi

  [ -f "$oldpath" ] || return 1		# need old file
  [ -f "$newpath" ] && return 1		# don't overwrite existing settings

  if [ "$copy" = 'y' ]; then
    cp "$oldpath" "$newpath" || die "ImportTV9Settings: Could not copy '$oldpath' to '$newpath'"
  else
    grep -v '\[bin  \]' "$oldpath" > "$newpath"
  fi
}

function ImportTV10Settings()
{
  local newpath="$TV_BASE_DIR/config/global.conf"
  local oldpath='/opt/teamviewer/config.old/global.conf'

  [ -f "$oldpath" ] || return 1		# need old file
  [ -f "$newpath" ] && return 1		# don't overwrite existing settings

  cp "$oldpath" "$newpath" || die "ImportTV10Settings: Could not copy '$oldpath' to '$newpath'"
}

function ImportTV10SettingsClient()
{
  local newpath="$TV_CFG_DIR/client.conf"
  local oldpath="${newpath/teamviewer/'teamviewer10/config'}"

  [ -f "$oldpath" ] || return 1		# need old file
  [ -f "$newpath" ] && return 1		# don't overwrite existing settings

  cp "$oldpath" "$newpath" || die "ImportTV10Settings: Could not copy '$oldpath' to '$newpath'"
}

#function ImportDefaults()
#{
#  local clientConf="$TV_CFG_DIR/client.conf"
#  local clientDflt="$TV_BASE_DIR/config/client.template.conf"
#
#  [ -f "$clientDflt" ] || return 0		# need template
#  [ -f "$clientConf" ] && return 0		# don't overwrite existing settings
#
#  cp "$clientDflt" "$clientConf" || die "ImportDefaults: Could not copy '$clientDflt' to '$clientConf'"
#}
