THIS_JDK='java-6-jdk'
NAME='JDK'

note() {
    printf "${blue}::${yellow} archlinux-java:${bold} $1${all_off}\n"
}

all_off="$(tput sgr0)"
bold="${all_off}$(tput bold)"
blue="${bold}$(tput setaf 4)"
yellow="${bold}$(tput setaf 3)"

update_desktop() {
    update-desktop-database -q
    update-mime-database /usr/share/mime >/dev/null
    xdg-icon-resource forceupdate &>/dev/null
    xdg-icon-resource forceupdate --theme HighContrast &>/dev/null
    xdg-icon-resource forceupdate --theme HighContrastInverse &>/dev/null
    xdg-icon-resource forceupdate --theme LowContrast &>/dev/null
}

fix_default() {
    if [[ -x /usr/bin/java ]]; then
        archlinux-java get
    else
        archlinux-java unset
    fi
}

post_install() {
    default=$(fix_default)
    case ${default} in
        "")
            archlinux-java set ${THIS_JDK}
            note "${NAME} ('${THIS_JDK}') set as default Java environment."
            ;;
        ${THIS_JDK})
            # Nothing
            note "${NAME} ('${THIS_JDK}') set as default Java environment."
            ;;
        *)
            note "Default Java environment already set to '${default}'.
                   To use ${NAME} ('${THIS_JDK}'), run:
                     # archlinux-java set ${THIS_JDK}
                   For status, use:
                     $ archlinux-java status"
            ;;
    esac

    if [[ ! -f /etc/ssl/certs/java/cacerts ]]; then
        init-jks-keystore
    fi

    update_desktop
}

post_upgrade() {
    post_install
}

pre_remove() {
    default=$(fix_default)
    if [[ ${default} = ${THIS_JDK} ]]; then
        archlinux-java unset
    fi
}

post_remove() {
    default=$(fix_default) # reassign
    if [[ ${default} ]]; then
        note "Default Java environment is '${default}'."
    else
        archlinux-java fix
        default=$(fix_default) # re-reassign
        if [[ ${default} ]]; then
            note "Default Java environment left as '${default}'."
        else
            note "Java environment unset."
        fi
    fi

    update_desktop
}
