#!/bin/bash
# This script is called after the cryfs .deb package is installed.
# It sets up the package source so the user gets automatic updates for cryfs.

# DEVELOPER WARNING: There is a lot of redundancy between this file and the install.sh script in the cryfs-web repository. Please port modifications to there!

set -e

DEBIAN_REPO_URL="http://apt.cryfs.org/debian"
UBUNTU_REPO_URL="http://apt.cryfs.org/ubuntu"

DISTRIBUTION=`lsb_release -s -i`
DISTRIBUTION_VERSION=`lsb_release -s -c`

containsElement () {
  local e
  for e in "${@:2}"; do  [[ "$e" == "$1" ]] && return 0; done
  return 1
}

get_repo_url () {
  if [[ "$DISTRIBUTION" == "Debian" ]] || [[ "$DISTRIBUTION" == "Devuan" ]]; then
    echo $DEBIAN_REPO_URL
  elif [[ "$DISTRIBUTION" == "Ubuntu" ]]; then
    echo $UBUNTU_REPO_URL
  else
    echo Not adding package source because $DISTRIBUTION is not supported. Please keep CryFS manually up to date. 1>&2
    exit 0
  fi
}

get_apt_config () {
  apt-config dump|grep "$1 "|sed -e "s/^$1\ \"\([^\"]*\)\"\;/\1/g"
}

sources_list_dir () {
  root=$(get_apt_config "Dir")
  etc=$(get_apt_config "Dir::Etc")
  sourceparts=$(get_apt_config "Dir::Etc::sourceparts")
  echo "$root/$etc/$sourceparts"
}

add_repository () {
  dir=$(sources_list_dir)
  repo_url=$(get_repo_url)
  echo "deb $repo_url $DISTRIBUTION_VERSION main" > $dir/cryfs.list
}

install_key () {
  # Key from http://www.cryfs.org/apt.key
  apt-key add - > /dev/null <<KEYEND
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1

mQINBFZxifMBEAC/KdA6/pf+0P7CMFPPxEPi9bVe8blG0xwMiFVeq9QOPYIjGsoO
vE/KsvqAN6ig1mMBfD7K9l2CZLX2srzSD3vHSg7btqciRVzKyEVasoNllKmqm8//
3UvYpqWL1mZkxtey5aSlcYxUo7+TyUK76hLjEiuT55ZHJeg9WZGWyoBzniRJ1zbl
FjYc44+5o1ec7lfEzIClU+IRw0t69j1x3BbClM57JSgmFu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LBxVx5i0RQMHQNtj2dGg1LYgVR
VZLzfvBhJkh1/uulaYWh4CYGTvLVf8Oihl/PIAonrweDQdXZCG6VvkxFx46/sCPg
oeO8NGKkrNFbA7ztQElqWkTuQs1tMgWvylCng2BrltPGKHqnAiYM1qAp2YdD+k9v
kd3Ppd9AfgaCg5T5Mks+rNMeDfprcC6FdiaJBV0QXasfSVCv5ph/YwRbrkM+tKAW
H9K51Myi7J9k5sIhsA1h6Bx3cjbNES4cnYUJEC2z6JmITzHP0uBWMwNoy9nykWpK
qswsGo4iD0syLOCkDIr2h0NKcCf0D20HPT8javVWz9cBfcKcXlSdO2Ju8+ONCrBe
ydEBA91yqM8k89fDUyhXI+e7hueUDZ+KUHC87wys82XyGQ/++AiPec3TTYVL2fiN
Q3mgKsOK0D/WziJdtL1i15CDUjhg0fUq4jNeHVnq7LUb/CmG7MB3jPI/jD+/pxGV
cGZtlxRJvXCjpaGJL0+AV0wE4rmkrpSAVC/9AeDi3l+tohUYB2WKOkXZEo90ShS2
cwOccYvBiIYhNMbgr5qsqPEJhcfdwXUpgJjZgFn9Y8ZwIJgjCEZllU2iEMKtbqwv
2oSFOf0c0GiV
=l3s3
-----END PGP PUBLIC KEY BLOCK-----
KEYEND
}

case "$1" in
    configure)
        install_key
        add_repository
    ;;

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

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

set +e

exit 0
