#!/bin/sh
#
# "sc_copy", "copy|delete|fipsRemaskKey|fipsCopyKey", "file|directory", file, peername, "", syn_pw, tofile
#
# cmd=$1
# ford=$2            # "file" or "directory"
# file=$3            # For FIPS, if $1=cmd=fipsRemaskKey|fipsCopyKey, file=filepath with no file extension|source filepath to copy from
# peername=$4 
# ""=$5
# $6   sync account password
# tofile=$7 # For FIPS case only. It is destination file to copy from 'file' in $3 if $1=cmd=fipsCopyKey.  Otherwise, it is "".


SYNC_CMD=/ca/bin/ssh
SYNC_OPT="-q -p 65519 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o Sync=$6 -o CheckHostIP=no -o PasswordAuthentication=yes"
STR_SYNC_DEL_WHITELIST="/tmp:/var/crash:/ca/appstore:/ca/fileshare/htdocs/client_sec/userresource:/ca/ssl/vhost"
RSYNC=/ca/sync/rsync

checkGoodPath() {
    DOT_DOT_THERE="`echo $1 | /usr/bin/egrep '\.\.'`"
    # The man page of egrep doesn't give an easy way to specify literal '.';
    # therefore, I had to include ',' in the list of valid chars.
    # 5/14/2008. Need '+' too now.
    INVALID_CHAR="`echo $1 | /usr/bin/egrep '[^+-9A-Z_a-z/.]'`"

    if [ -n "$DOT_DOT_THERE" ]; then
        echo "$1: Bad path"
        exit 1
    fi

    if [ -n "$INVALID_CHAR" ]; then
        echo "$1: Bad path"
        exit 1
    fi
}

checkDelPath()
{
    echo "$file|"$STR_SYNC_DEL_WHITELIST | awk 'BEGIN { FS = "|" } {
        split($2, arr_del, ":")
        found=0
        for(k in arr_del) {
            if(index($1, arr_del[k]) == 1) {
                found=1
            }
        }
        if(found == 1) {
            print "Y"
        } else {
            print "N"
        }
    }'
}

do_fileop() {
case "$cmd" in
"copy")
    if [ ! -e "$file" ]; then
        echo "$0: error: file not exists"
        exit 1
    fi
    dirname=`/usr/bin/dirname $file`
 
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'if [ ! -e $dirname ]; then mkdir -p $dirname; fi' > /dev/null 2>&1"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chmod a+w $dirname' > /dev/null 2>&1"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'if [ -e $file ]; then rm -f $file; fi' > /dev/null 2>&1"
 
    result_stat=`stat -c "%A" ${file}`
    result_group=`echo ${result_stat:4:3}`
    is_sslkey=`echo ${result_group} | grep "^r"`

    # NOTE: Always set source file to 'group read' permission or it will not work for ECC/FIPS file sync.
    /ca/sync/munch -x "chmod g+r ${file}" > /dev/null 2>&1

    # echo "sc_copy: (copy) Copying $file to peer=$ssh_peername..."
    $RSYNC -Wrzop --rsh="$SYNC_CMD $SYNC_OPT" \
         --rsync-path=$RSYNC \
         $file $peername:$file
    if [ -z "${is_sslkey}" ];then
	 	 /ca/sync/munch -x "chmod g+r ${file}" > /dev/null 2>&1
         $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'chmod g+r ${file}' > /dev/null 2>&1"
	    # echo "sc_copy: (copy) Changing $file to to have group read permission."
    fi

    #$SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'chmod g+r ${file}' > /dev/null 2>&1"

    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'chown root ${file}' > /dev/null 2>&1"
    ret=`echo ${file} | sed -n '/^\/ca\/fileshare\/htdocs\/client_sec\/userresource.*/p'`
    if [ "$ret" = "$file" ]; then
        $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chmod a+w $file' > /dev/null 2>&1"
    fi
    ;;
"delete")
    ret=`checkDelPath`
    if [ $ret = "N" ]; then
        echo "$0: error: only the files in directory of [$STR_SYNC_DEL_WHITELIST] support synconfig delete"
        exit 1
    fi

    rm -f "$file"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'if [ -e "$file" ]; then rm -f "$file"; fi' > /dev/null 2>&1"
    ;;
"fipsRemaskKey")
    dirname=`/usr/bin/dirname $file`

	# Make sure a directory like vhost_certs exists.
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'if [ ! -d $dirname ]; then /bin/mkdir -p 655 $dirname; fi' > /tmp/fipsRemaskKey.txt 2>&1"
 
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chmod a+w $dirname' > /dev/null 2>&1"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chown -R root $dirname' > /dev/null 2>&1"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chmod -R g+r $dirname' > /dev/null 2>&1"

	# NOTE: Always set source file to 'group read' permission or it will not work for ECC/FIPS file sync.
	/ca/sync/munch -x "chmod g+r ${file}" > /dev/null 2>&1

    # echo "sc_copy: (fipsRemaskKey) Remasking peer keyfile=$file..."
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/fips_sync remaskVhostKeys $file > /tmp/remaskVhostKeys.txt 2>&1"

    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chmod -R g+r $dirname' > /dev/null 2>&1"
    ;;
"fipsCopyKey")
    dirname=`/usr/bin/dirname $file`
 
	# NOTE: Always set source file to 'group read' permission or it will not work for ECC/FIPS file sync.
	/ca/sync/munch -x "chmod g+r ${file}" > /dev/null 2>&1

    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x '/bin/chmod a+w $dirname' > /dev/null 2>&1"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'chown -R root $dirname' > /dev/null 2>&1"
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'chmod -R g+r $dirname' > /dev/null 2>&1"
 
    # echo "sc_copy: (fipsCopyKey) Copying keyfile from=$file, to=$tofile..."
    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/fips_sync copyVhostKeys $file $tofile >> /tmp/copyVhostKeys.txt 2>&1"
    #$SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'if [ -e $file ]; then cp -f $file $tofile; fi' > /tmp/fipsCopyKey.txt 2>&1"

    $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'chmod -R g+r $dirname' > /dev/null 2>&1"
    ;;
esac
}

do_dirop() {
case "$cmd" in
"copy")
    if [ ! -e "$file" ]; then
        echo "$0: error: dir not exists"
        exit 1
    fi
    $RSYNC -Wrzop --rsh="$SYNC_CMD $SYNC_OPT" \
         --rsync-path=$RSYNC \
         $file/ $peername:$file/
    ;;
"delete")
    ret=`checkDelPath` 
    if [ $ret = "N" ]; then
        echo "$0: error: only the sub-directoris in directory of [$STR_SYNC_DEL_WHITELIST] support synconfig delete"
        exit 1
    fi

    if [ ! -d "$file" ]; then
        echo "$0: error: directory not exists"
        exit 1
    fi
    if [ "$file" != "/tmp" -a "$file" != "/tmp/" ]; then
      /bin/rm -rf $file
      $SYNC_CMD $SYNC_OPT $ssh_peername "/ca/sync/munch -x 'if [ -d $file ]; then rm -rf $file; fi' > /dev/null 2>&1"
    fi
    ;;
*)
    echo "$0: error: Unknown Option"
    ;;
esac
}

# Pick up arguments from command line here.
cmd=$1
ford=$2            # "file" or "directory"
file=$3
peername=$4
tofile=$7          # For FIPS case only. It is destination file to copy from 'file' in $3 if $1=cmd=fipsCopyKey.  Otherwise, it is "".

ssh_peername=`echo $peername | tr -d "[]"`

ping_opt="-n -c 1 -t 3"
if [ -n "`echo $ssh_peername |grep :`" ]
then
    PING=ping6
else 
    PING=ping
fi 

STATUS=`$PING $ping_opt $ssh_peername | grep "100.*% packet loss"`
if [ "x$STATUS" != "x" ]
then
    echo  "sc_copy: $ssh_peername is unreachable" >> /ca/sync/log/local_script.log
    exit 0
fi

case "$ford" in
"file")
    checkGoodPath $file
    do_fileop
    ;;
"directory")
    checkGoodPath $file/fileplaceholder
    do_dirop
    ;;
*)
    echo "$0: error: Unknown Option"
    ;;
esac

exit 0

