#!/bin/sh

# Find the CPU architecture
synoinfo=`get_key_value /etc.defaults/synoinfo.conf unique`
arch=`echo $synoinfo | cut -d_ -f2`
[ $arch = 88f6282 ] && arch=88f6281
isUpgrade=/tmp/mc.upgrade

preinst ()
{
    # Check if the architecture is supported
    case $arch in
        88f5281|88f6281|powerpc|ppc824x|ppc853x|ppc854x|x86)
            true
            ;;
        *)
            cat << EOM
Your architecture is not supported by this package, sorry.
Architecture  : $arch
Synology info : $synoinfo
EOM
        exit 1
            ;;
    esac

    exit 0
}

postinst ()
{
    # Create the view directory
    mkdir -p /usr/local/mc
    mkdir -p /usr/local/bin

    # Create symlinks to the installation ditectory
    ln -s ${SYNOPKG_PKGDEST}/bin-$arch /usr/local/mc/bin
    ln -s ${SYNOPKG_PKGDEST}/etc /usr/local/mc/etc
    ln -s ${SYNOPKG_PKGDEST}/lib-$arch /usr/local/mc/lib
    ln -s ${SYNOPKG_PKGDEST}/libexec-$arch /usr/local/mc/libexec
    ln -s ${SYNOPKG_PKGDEST}/share /usr/local/mc/share

    # Create symlinks to utils
    for bin in mc
    do
      ln -s ${SYNOPKG_PKGDEST}/bin-$arch/$bin /usr/local/bin/$bin
    done

    # Build the magic file
    (
      cd /usr/local/mc/share/misc
      tar xzpf magic.tgz
      /usr/local/mc/bin/file -C
      rm -fr magic magic.tgz
    )
    
    # Correct the files permission and ownership
    chmod 555 /usr/local/mc/bin/*
    chmod 555 /usr/local/mc/lib/*
    chmod 555 /usr/local/mc/libexec/mc/*
    chmod 555 /usr/local/mc/libexec/mc/*/[a-z]*
    chown -R root:root /usr/local/mc

    exit 0
}

preuninst ()
{
    exit 0
}

postuninst ()
{
    # Remove symlinks to utils
    for bin in mc
    do
      rm /usr/local/bin/$bin
    done

    # Remove symlinks from /usr/local/mc
    rm /usr/local/mc/bin
    rm /usr/local/mc/etc
    rm /usr/local/mc/lib
    rm /usr/local/mc/libexec
    rm /usr/local/mc/share

    # Remove the view directory
    rmdir /usr/local/mc

    exit 0
}

preupgrade ()
{
    exit 0
}

postupgrade ()
{
    exit 0
}
